преобразуйте список объектов от одного типа до другого лямбда-выражения использования

У меня есть цикл foreach, читая список объектов одного типа и производя список объектов другого типа. Мне сказали, что лямбда-выражение может достигнуть того же результата.

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

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

Любая справка ценилась бы - я плохо знаком с лямбдой и linq спасибо, s

200
задан Ian P 15 December 2009 в 08:08
поделиться

5 ответов

Try the following

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

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. The .ToList call is an extension method which will convert this IEnumerable into a List.

290
ответ дан 23 November 2019 в 05:05
поделиться

I believe something like this should work:

origList.Select(a => new TargetType() { SomeValue = a.SomeValue});
14
ответ дан 23 November 2019 в 05:05
поделиться

If you know you want to convert from List to List then List.ConvertAll will be slightly more efficient than Select/ToList because it knows the exact size to start with:

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

In the more general case when you only know about the source as an IEnumerable, using Select/ToList is the way to go. You could also argue that in a world with LINQ, it's more idiomatic to start with... but it's worth at least being aware of the ConvertAll option.

211
ответ дан 23 November 2019 в 05:05
поделиться

Вот простой пример ..

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

List<string> s = c.Select(x => x.ToString()).ToList();
9
ответ дан 23 November 2019 в 05:05
поделиться
var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
7
ответ дан 23 November 2019 в 05:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: