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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With