转换对象的列表从一种类型到另一个使用lambda表达式 [英] convert a list of objects from one type to another using lambda expression
问题描述
我有一个foreach循环读取一种类型的对象的列表,并产生一个不同类型的对象的列表。我被告知,一个lambda表达式可以达到同样的效果。
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});
}
任何帮助将是appreciated-我是新来的lambda和LINQ
感谢,
S
Any help would be appreciated- i'm new to lambda and linq thanks, s
推荐答案
请尝试以下
var targetList = origList
.Select(x => new TargetType() { SomeValue = x.SomeValue })
.ToList();
这是使用Lambda表达式和LINQ的组合来实现该解决方案。选择功能是将原来的集合中应用传递委托(或lambda在这种情况下)的每一个值的投影式的方法。其结果将在一个新的返回的IEnumerable<&的TargetType GT;
。该.ToList调用是一个扩展方法,将它转换的IEnumerable< TargetType的>
到列表< TargetType的>
。
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>
.
这篇关于转换对象的列表从一种类型到另一个使用lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!