Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
        }
like image 658
AsValeO Avatar asked Sep 20 '16 20:09

AsValeO


2 Answers

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());
like image 113
Nico Avatar answered Sep 18 '22 00:09

Nico


You can use OfType extension:

var dogs = lst.OfType<Dog>().ToList();
var cats = lst.OfType<Cat>().ToList();
var parrots = lst.OfType<Carrot>().ToList();
like image 45
Arturo Menchaca Avatar answered Sep 21 '22 00:09

Arturo Menchaca