AsValeO AsValeO - 1 year ago 135
C# Question

C# split List of interface by implementations

I need to split

to get lists of concrete implementations of
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 Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download