LINQ在哪里查询不同派生类的集合

时间:2010-07-09 14:12:32

标签: linq

我有一组来自同一父母的不同对象。

如何从包含混合类型

的集合中提取特定类型的对象

e.g。

public class A {}
public class B : A {}
public class C : A {}

该集合将包含B和C类型的对象

我在那里只需要帮助填写'[]'位

var x = from xTypes in xCollection where '[type of object is type B]' select xTypes;

感谢。

2 个答案:

答案 0 :(得分:5)

您应该使用OfType<T>扩展方法而不是LINQ查询语法:

var x = xCollection.OfType<B>();

这会给你一个IEnumerable<B>。如果您确实想使用LINQ查询语法,则必须执行以下操作:

var x = from obj in xCollection where obj is B select (B)obj;

答案 1 :(得分:3)

var x = from xTypes in xCollection 
        where xTypes is B 
        select xTypes;

或者如果您想要这种类型而不是任何派生类型:

var x = from xTypes in xCollection 
        where xTypes.GetType() == typeof(B) 
        select xTypes;
相关问题