开发者

LINQ where query on collection of different derived classes

I have a collection of different objects that derive from the same parent.

How can I extract objects of a particular type from a collection containing mixed types

e.g.

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

The collection will contain objects of type B and C

I'm halfway there just need help filling in the '[]' bi开发者_StackOverflow中文版t

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

Thanks.


You should use the OfType<T> extension method rather than LINQ query syntax for this:

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

This will give you back an IEnumerable<B>. If you do want to use the LINQ query syntax, you'd have to do this:

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


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

or if you want exactly this type and not any derived types:

var x = from xTypes in xCollection 
        where xTypes.GetType() == typeof(B) 
        select xTypes;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜