简体   繁体   English

使用linq过滤可观察的集合

[英]Filter a observable collection using linq

I have an animal class. 我有动物课。 A herbivore class which inherits from animal and an elephant class which inherits from herbivore . 从动物继承的herbivore类和从herbivore动物继承的elephant类。 I also have a carnivore class which inherits from animal and a tiger class which inherits from carnivore . 我也有一个从animal继承的carnivore类和一个从carnivore继承的tiger类。 I Have a observable collection called zoo with tigers and elephants. 我有一个可观察到的收藏,叫做动物园,里面有老虎和大象。 I Want to select the Herbivores in the zoo collection. 我想在动物园收藏中选择草食动物。 I Then want to add the herbivores to a new observable collection called herb. 然后,我想将草食动物添加到一个称为herb的新的可观察集合中。

var herbivores = from Animal in zoo
                 where Animal == Animal.OfType<Herbivore>()
                 select Animal;

foreach (var item in herbivores)
{
    herb.Add(item);
}                        

You can't use OfType like that; 您不能像这样使用OfType it's an extension method on an enumerable collection, not on the class animal . 它是可枚举集合的扩展方法,而不是class animal的扩展方法。 Do this instead: 改为这样做:

var herbivores = zoo.OfType<Herbivore>();

Alternatively you could achieve the same effect with 另外,您也可以使用

var herbivores = zoo.Where(a => a is Herbivore);

but there really is no point in doing this the funky way. 但是这样做确实没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM