Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic parent Collection split to child collections

I have a list of IAnimal

List<IAnimal> Animals

Inside this list I have 3 different Animal

  1. Cat 5 objects
  2. Dog 10 objects
  3. Cow 3 objects

How can I generate 3 different lists of the sub Animal type?

Result should be

  1. List<Cat> Cats contains 5 objects
  2. List<Dog> Dogs contains 10 objects
  3. List<Cow> Cows contains 3 objects

I don't mind of using different collection type then List. IEnumerable or any others?

like image 266
Maro Avatar asked Dec 26 '22 07:12

Maro


1 Answers

LINQ makes this simple:

var cats = animals.OfType<Cat>().ToList();
var dogs = animals.OfType<Dog>().ToList();
var cows = animals.OfType<Cow>().ToList();
like image 188
Jon Skeet Avatar answered Jan 19 '23 01:01

Jon Skeet