LINQ - Getting a subset based on type [duplicate]
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?
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.)
Something like this should work.
var animals = new List<Animals> { new Dog(), new Cat(), new Pig(), }; //etc.
var dogs =
animals
.OfType<Dog>()
.ToList();
精彩评论