且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 lambda 表达式将对象列表从一种类型转换为另一种类型

更新时间:2022-06-15 22:36:20

尝试以下方法

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

这是结合使用 Lambdas 和 LINQ 来实现的解决方案.Select 函数是一种投影样式方法,它将传入的委托(在本例中为 lambda)应用于原始集合中的每个值.结果将在新的 IEnumerable 中返回..ToList 调用是一个扩展方法,它将把这个 IEnumerable 转换成一个 List.

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>.