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

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

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

当前回答

这里有一个简单的例子。

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

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

其他回答

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

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
var target = origList.ConvertAll(x => (TargetType)x);

这里有一个简单的例子。

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

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

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

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

我相信这样做是可行的:

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