How can I intelligently create a List<int> from an IEnumerable<CustomClass>, if CustomClass has a property of type int, called customProperty which I wish to use to create my List<int> ?
I know I can create a List<CustomClass> by calling instance.ToList<CustomClass>();
How can I extract the property info to populate my list? What is best practice here ?
Using Linq, you can project to the property and
ToList()the resultingIEnumerable<int>:If you have never seen Linq extension methods before,
Selectis a common “projection” method. It takes a lambda expression, in this case an expression taking a typeCustomClassrepresented asc, it returns whatever you want it to, in this case anint. AsSelectis working on a set (enumerable of something) you actually get anIEnumerable<int>in response, it can infer the type ofIEnumerablebased on yourSelectlambda.If you want a delay-run
IEnumerable<int>, simply drop theToList()call.I never like to impart opinion on best practice, but this is a clean one-liner that clearly shows intent (assuming basic understanding of Linq) and I see it all over the place.
Linq Resources:
http://www.codeproject.com/Articles/84521/LINQ-for-the-Beginner
http://www.codeproject.com/Articles/19154/Understanding-LINQ-C
Lambda Expression Resources:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
Alternatively, these topics are very easily searched with terms like “LINQ tutorials” or “lambda expression tutorials”.