c# - 获取 List<T> 中变量的 List<string>

标签 c# asp.net-mvc list ef-code-first

我目前有一个 List<T>由以下类组成:

int id { get; set; }
string title { get; set; }
string description { get; set; }

我想创建一个 List<string>只有所有标题在列表中

执行此操作的最佳性能方法是什么?

编辑 我的描述字段平均 2k 个字符...我不希望这会减慢获取标题的速度。

编辑2 我首先使用 MVC 的代码( Entity Framework )。 List<T>存储在 _context 中,我从中查询以获取数据。

Edit3 如果可能的话..有没有办法获得标题和 ID?

最佳答案

I want to create a List<string> of only all the title's in the List

您可以通过 Select 使用投影.

var list = new List<SomeClass>();

var titleList = list.Select(x => x.title).ToList();

参见 Getting Started with LINQ in C#有关 LINQ 扩展方法的更多信息。

IF possible .. Is there a way to get the Title AND ID ?

您可以使用 Anonymous Type将所有三个属性放在一个列表中:

var entityList = list.Select(x => new { x.title, x.id, x.description }).ToList();

Which would be the best performance way to do this?

var list = new List<SomeClass>();
var titleList = new List<string>(list.Count);

foreach(var item in list)
{
    titleList.Add(item.title);
}

LINQ 不会胜过简单的 foreach声明,但这是您应该通过基准测试评估的权衡,因为在大多数情况下差异可以忽略不计。

Microbenchmark

关于c# - 获取 List<T> 中变量的 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358281/

相关文章:

C# 如何从 NoSuchElementException 获取方法和选择器

c# - ASP.net 页面只允许在服务器上执行吗?

javascript - 在 JavaScript 中构建类似 LINQ 的查询 API

c# - 如何检查修改了哪些属性/条目,哪些不在 EF 6 中编辑记录

java - 添加原始 Int 而不是 Int 对象有任何风险吗?

c# - 如何使用 Team Foundation Server 对象模型获取可编写脚本的构建定义?

c# - 检测 HTML 字符串是否包含 C# 中的可见文本

asp.net-mvc - 无法在主机上加载程序集 WebPages.Deployment 版本 2?

php - 仅带css的样式列表,不带js等

python打印逐行递​​增的列表项