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();
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