我有一个foreach循环,读取一种类型的对象列表,并产生另一种类型的对象列表。有人告诉我,lambda表达式可以实现相同的结果。

var origList = List<OrigType>(); // assume populated
var targetList = List<TargetType>(); 

foreach(OrigType a in origList) {
    targetList.Add(new TargetType() {SomeValue = a.SomeValue});
}

当前回答

假设您有多个要转换的属性。

public class OrigType{
    public string Prop1A {get;set;}
    public string Prop1B {get;set;}
}

public class TargetType{
    public string Prop2A {get;set;}
    public string Prop2B {get;set;}
}

var list1 = new List<OrigType>();
var list2 = new List<TargetType>();

list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })

其他回答

试试下面的方法

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

这是使用Lambdas和LINQ的组合来实现解决方案。Select函数是一个投影风格的方法,它将传入的委托(在本例中为lambda)应用到原始集合中的每个值。结果将以新的IEnumerable<TargetType>形式返回。. tolist调用是一个扩展方法,它将IEnumerable<TargetType>转换为List<TargetType>。

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));

如果需要使用函数进行类型转换:

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list2 = list1.ConvertAll(x => myConvertFuntion(x));

我的自定义函数是:

private Type2 myConvertFunction(Type1 obj){
   //do something to cast Type1 into Type2
   return new Type2();
}

这里有一个简单的例子。

List<char> c = new List<char>() { 'A', 'B', 'C' };

List<string> s = c.Select(x => x.ToString()).ToList();

我相信这样做是可行的:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});