开发者

LINQ - Getting a subset based on type [duplicate]

This question already has answers here: LINQ: From a list of type T, retrieve only objects of a certain subclass S (4 answers) Closed 9 years ago. 开发者_C百科

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜