我目前有一个 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
声明,但这是您应该通过基准测试评估的权衡,因为在大多数情况下差异可以忽略不计。
关于c# - 获取 List<T> 中变量的 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18358281/