Problem
I have a foreach loop that reads a list of one type of item and produces a list of another type of object. A lambda expression, I was told, can achieve the same outcome.
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
Asked by Stratton
Solution #1
Try the following
var targetList = origList
.Select(x => new TargetType() { SomeValue = x.SomeValue })
.ToList();
To do this, a combination of Lambdas and LINQ is used. The Select function is a projection-style method that applies the delegate (or lambda in this example) to each value in the original collection. In a new IEnumerableTargetType>, the result will be returned. This IEnumerableTargetType> will be converted to a ListTargetType> using the.ToList call, which is an extension method.
Answered by JaredPar
Solution #2
If you’re sure you want to go from ListT1> to ListT2>, use ListT>. Because it knows the precise size to begin with, ConvertAll will be slightly more efficient than Select/ToList:
target = orig.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });
Select/ToList is the method to do in the more general instance when you only know about the source as an IEnumerableT>. You could argue that in a world with LINQ, it’s more idiomatic to begin with… but it’s worth knowing about the ConvertAll option at the very least.
Answered by Jon Skeet
Solution #3
var target = origList.ConvertAll(x => (TargetType)x);
Answered by Alp
Solution #4
List<target> targetList = new List<target>(originalList.Cast<target>());
Answered by Pranav
Solution #5
Something along these lines, in my opinion, should work:
origList.Select(a => new TargetType() { SomeValue = a.SomeValue});
Answered by Andy White
Post is based on https://stackoverflow.com/questions/1909268/convert-a-list-of-objects-from-one-type-to-another-using-lambda-expression