Create list of T2 from list of T1, using T2's constructor that requires T1

Viewed 133

If I get a list of Type1 from method GetType1List

List<Type1> Type1List = GetType1List();

I can then create a list of Type2 and cycle through the first list using foreach to add new Type2 using its constructor which requires a Type1 instance:

List<Type2> Type2List = new List<Type2>();
foreach(Type1 type1 in Type1List)
{
    Type2List.Add(new Type2(Type1));
}

Is there any way I can wrap this up without creating the initial list of Type1 and without the foreach loop?

3 Answers

Using LINQ Select:

List<Type2> Type2List = Type1List
    .Select(type1 => new Type2(type1))
    .ToList();

You can use Linq:

var TypeList2 = GetType1List().Select(type1 => new Type2(type1)).ToList();

The easiest way seems to be List<T>.ConvertAll() method, without using System.Linq reference

var Type1List = GetType1List();
var Type2List = Type1List.ConvertAll(t1 => new Type2(t1));
Related