2010-07-09 91 views
1

我有从同一个父派生的不同对象的集合。LINQ其中查询不同派生类的集合

如何可以提取特定类型的对象从一个集合含有混合类型

例如

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; 

感谢。

回答

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; 
+0

我喜欢扩展方法。更干净。谢谢。 – empo 2010-07-09 14:27:04

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;