Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Getting a subset based on type [duplicate]

Tags:

c#

linq

I have a List<Animal> which contains objects of type Cat, Dog and Pig (For simplicity)

I wish to select all the Dogs into a new List<Dog> from my List<Animal>.

How is that done in LINQ?

like image 389
Ian Vink Avatar asked Dec 22 '22 09:12

Ian Vink


2 Answers

You can use Enumerable.OfType<T>:

var dogs = animals.OfType<Dog>().ToList();

(Note that the ToList() is only required to make a List<Dog>. If you just need IEnumerable<Dog>, you can leave it off.)

like image 154
Reed Copsey Avatar answered Dec 24 '22 03:12

Reed Copsey


Something like this should work.

var animals = new List<Animals> { new Dog(), new Cat(), new Pig(), }; //etc.
var dogs = 
  animals
  .OfType<Dog>()
  .ToList();
like image 32
DaveShaw Avatar answered Dec 24 '22 01:12

DaveShaw