使用 lambda 表达式将对象列表从一种类型转换为另一种类型 [英] convert a list of objects from one type to another using lambda expression

查看:50
本文介绍了使用 lambda 表达式将对象列表从一种类型转换为另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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});
}

任何帮助将不胜感激 - 我是 lambda 和 linq 的新手谢谢,

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();

这是结合使用 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>.

这篇关于使用 lambda 表达式将对象列表从一种类型转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆