AsValeO AsValeO - 2 months ago 12
C# Question

C# split List of interface by implementations

I need to split

List<IInterface>
to get lists of concrete implementations of
IInterface
.
How can I do it in optimal way?

public interface IPet { }
public class Dog :IPet { }
public class Cat : IPet { }
public class Parrot : IPet { }

public void Act()
{
var lst = new List<IPet>() {new Dog(),new Cat(),new Parrot()};
// I need to get three lists that hold each implementation of IPet: List<Dog>, List<Cat>, List<Parrot>
}

Answer

You could do a GroupBy by type:

var grouped = lst.GroupBy(i => i.GetType()).Select(g => g.ToList()).ToList()

If you want a dictionary by type you could do:

var grouped = lst.GroupBy(i => i.GetType()).ToDictionary(g => g.Key, g => g.ToList());
var dogList = grouped[typeof(Dog)];

Or as Tim suggested in a comment:

var grouped = lst.ToLookup(i => i.GetType());