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>
}
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());
You can use OfType extension:
var dogs = lst.OfType<Dog>().ToList();
var cats = lst.OfType<Cat>().ToList();
var parrots = lst.OfType<Carrot>().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With