Get a List<string> of variables within a List<T>
asp.net-mvc, c#, ef-code-first, list
Solution
I want to create a `List<string>` of only all the title's in the List
You can use projection via `Select`.
var list = new List<SomeClass>();
var titleList = list.Select(x => x.title).ToList();
See Getting Started with LINQ in C# for more information on LINQ extension methods.
IF possible .. Is there a way to get the Title AND ID ?
You can use an Anonymous Type to put all three properties in one list:
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 will not outperform a simple `foreach` statement, but that's a tradeoff you should evaluate by benchmarking since the difference is negligible in most cases.
Microbenchmark
Problem
I currently have a `List<T>` made up of the following class: ``` int id { get; set; } string title { get; set; } string description { get; set; } ``` I want to create a `List<string>` of only all the title's in the List Which would be the best performance way to do this? Edit My Description field averages 2k characters... I dont want that to slow down only getting titles. Edit2 I am using MVC's Code first (Entity Framework). The `List<T>` is stored in the _context, which I query from to get the data. Edit3 IF possible .. Is there a way to get the Title AND ID ?