How will works this different ways to select a subset in a list by type

时间:2017-05-16 09:28:49

标签: c# performance linq

I have defined a collection of an interface that stores a lot of different implementations. Then I need to retrieve only the subset of one of these implementations. And I need this subset to by typed with the implementation type (not the interface).

I can think of a lot of way to do so but I wonder which one is the more efficient. By saying that, I am aware that efficient can take a lot of meaning (complexity, memory/CPU eating, etc).

So in other words: can you tell me how will perform these operations?

var myList = new List<IFoo>();

This is the first thing I thought about:

var mySubSet = myList.Where(f => f is FooImpl).Cast<FooImpl>();

But when I was typing it, I thought: "this will do the cast twice, bad idea". Am I wrong ?

So I thought to:

var mySubSet = myList.Select(f => f as FooImpl1).Where(f => f != null);

And of course, there is the old fashion way with a manual loop:

var mySubSet = new List<FooImpl1>();
foreach(var foo in myList)
{
    var fooImpl1 = foo as FooImpl1;
    if(fooImpl1 != null)
    {
        mySubSet.Add(fooImpl1);
    }
}

There is probably a lots of other ways to do this, so do not hesitate to improve my question.

1 个答案:

答案 0 :(得分:3)

var mySubSet = myList.Where(f => f is FooImpl).Cast<FooImpl>();

But when I was typing it, I thought: "this will do the cast twice, bad idea". Am I wrong ?

It doesn't do the cast twice, but it's not the best approach anyway.

You can use Enumerable.OfType which filters and casts at the same time:

var mySubSet = myList.OfType<FooImpl>().ToList();

This is not really more efficient but more readable (which can also mean work-efficiency).