tags:

views:

25

answers:

2

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 '[]' bit

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

Thanks.

+2  A: 
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;
Darin Dimitrov
+4  A: 

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;
Adam Robinson
I like the extension method. Much cleaner. Thank you.
empo