Question

I have TypeA and B like this:

class TypeA
{

prop 1;
prop 2;
prop 3;
prop 4;
...
prop 15;
}

class TypeB
{

prop a;
prop b;
prop c;
...
prop p;
}

Each property value from TypeB will be constructed by manipulating some properties of TypeA.

Now I need to do something like

List<TypeB> list= SomeConverter(List<TypeA>);

Source list may contain around 5000 objects.

I would like to know the fastest way to do this. Code readability is not my concern.

There are few such types that I need to map.

Thanks

Was it helpful?

Solution

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.

OTHER TIPS

AutoMapper is a decent library for such cases, didn't try it in huge lists, give it a try.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top