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

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

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

当前回答

或者使用构造函数& linq选择:

public class TargetType {
  public string Prop1 {get;set;}
  public string Prop1 {get;set;}

  // Constructor
  public TargetType(OrigType origType) {
    Prop1 = origType.Prop1;
    Prop2 = origType.Prop2;
  }
}

var origList = new List<OrigType>();
var targetList = origList.Select(s=> new TargetType(s)).ToList();  

Linq线条更柔和!: -)

其他回答

对于类似类型的类。

<targetlist> targetlst= jsoninvert . deserializeinct <targetlist> (JsonConvert.SerializeObject . <List<baselist>);

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

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

或者使用构造函数& linq选择:

public class TargetType {
  public string Prop1 {get;set;}
  public string Prop1 {get;set;}

  // Constructor
  public TargetType(OrigType origType) {
    Prop1 = origType.Prop1;
    Prop2 = origType.Prop2;
  }
}

var origList = new List<OrigType>();
var targetList = origList.Select(s=> new TargetType(s)).ToList();  

Linq线条更柔和!: -)

List<target> targetList = new List<target>(originalList.Cast<target>());

如果类型可以直接转换,这是最干净的方法:

var target = yourList.ConvertAll(x => (TargetType)x);

如果不能直接转换类型,则可以将属性从原始类型映射到目标类型。

var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });