You won't be able to avoid the cost of converting each instance of TypeA
to an instance of TypeB
, but you can avoid the cost of resizing the list by setting an initial capacity:
List<TypeB> listB = new List<TypeB>(listA.Count);
listB.AddRange(listA.Select(SomeConverter));
TypeB SomeConverter(TypeA input)
{
return new TypeA() { ... };
}
Or this, for slightly better performance:
List<TypeB> listB = new List<TypeB>(listA.Count);
foreach(var a in listA)
{
listB.Add(SomeConverter(a));
}
Of course, in many cases the biggest performance comes from over-zealously using lists in the first place. For example, calling ToList()
when invoking a Linq query forces the query to be evaluated immediately, and the results saved into a List<T>
. Instead, if you can defer evaluation until as late as possible, you'll usually avoid much of the most expensive processing. In general, unless you really need to do dynamic insert / deletes to the set, you almost certainly should avoid using lists.