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

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

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

当前回答

对于类似类型的类。

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

我们将考虑第一个列表类型是字符串,并希望将其转换为整数类型的列表。

List<String> origList = new ArrayList<>(); // assume populated

在原始列表中添加值。

origList.add("1");
origList.add("2");
    origList.add("3");
    origList.add("4");
    origList.add("8");

创建Integer类型的目标列表

List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());

使用forEach打印列表值:

    targetLambdaList.forEach(System.out::println);

如果你知道你想从List<T1>转换到List<T2>,那么List<T>。ConvertAll将比Select/ToList更有效,因为它知道开始时的确切大小:

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

在更一般的情况下,当您只知道源为IEnumerable<T>时,使用Select/ToList是可行的方法。你也可以争辩说,在LINQ的世界里,更习惯的开始是……但至少有必要了解ConvertAll选项。

或者使用构造函数& 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线条更柔和!: -)

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

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