LINQ按对象类型选择 [英] LINQ selection by type of an object

查看:53
本文介绍了LINQ按对象类型选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两种类型的对象A和A的集合. B.

I have a collection which contains two type of objects A & B.

Class Base{}
Class A : Base {}
Class B : Base {}

List<Base> collection = new List<Base>();
collection.Add(new A());
collection.Add(new B());
collection.Add(new A());
collection.Add(new A());
collection.Add(new B());

现在,我要根据集合的类型(A或B,而不是两者)选择对象.

Now I want to select the objects from the collection based on its type (A or B, not both).

如何为此编写LINQ查询?请帮我.否则,我需要遍历我不想要的集合.谢谢.

How I can write a LINQ query for this? Please help me. Otherwise I need to loop through the collection, which I dont want to. Thanks.

谢谢大家的帮助.现在,我可以使用LINQ的OfType()了.但我认为在我的情况下它行不通.我的情况是

Thank you all for your help. Now I can use OfType() from LINQ. But I think in my case it wont work. My situation is

Class Container
{
  List<Base> bases;
}

List<Container> containers = new List<Container>();

现在,我要从具有至少一种类型A的容器中选择容器.也许这不能由LINQ完成.非常感谢.

Now I want to select the container from containers, which has at least one type A. May be this cant be done by LINQ. Thanks a lot.

推荐答案

您可以使用

You can use the OfType Linq method for that:

var ofTypeA = collection.OfType<A>();

关于您不愿意在整个收藏中循环浏览,您应该记住Linq不会做魔术.我没有检查OfType的实现,但是不是在其中找到循环或迭代器会感到惊讶.

Regarding your unwillingness to loop throught the collection, you should keep in mind that Linq does not do magic tricks; I didn't check the implementation of OfType, but I would be surprised not to find a loop or iterator in there.

这篇关于LINQ按对象类型选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆