Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a list of objects from one type to another using lambda expression

I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result.

var origList = List<OrigType>(); // assume populated var targetList = List<TargetType>();   foreach(OrigType a in origList) {     targetList.Add(new TargetType() {SomeValue = a.SomeValue}); } 

Any help would be appreciated- i'm new to lambda and linq thanks, s

like image 760
Stratton Avatar asked Dec 15 '09 18:12

Stratton


People also ask

How do I convert from one type to another in C#?

Objects can be converted from one type to another, assuming that the types are compatible. Often this is achieved using implicit conversion or explicitly with the cast operator. An alternative to this is the use of the "as" operator.


2 Answers

Try the following

var targetList = origList   .Select(x => new TargetType() { SomeValue = x.SomeValue })   .ToList(); 

This is using a combination of Lambdas and LINQ to achieve the solution. The Select function is a projection style method which will apply the passed in delegate (or lambda in this case) to every value in the original collection. The result will be returned in a new IEnumerable<TargetType>. The .ToList call is an extension method which will convert this IEnumerable<TargetType> into a List<TargetType>.

like image 195
JaredPar Avatar answered Oct 05 '22 07:10

JaredPar


If you know you want to convert from List<T1> to List<T2> then List<T>.ConvertAll will be slightly more efficient than Select/ToList because it knows the exact size to start with:

target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue }); 

In the more general case when you only know about the source as an IEnumerable<T>, using Select/ToList is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll option.

like image 44
Jon Skeet Avatar answered Oct 05 '22 05:10

Jon Skeet