tags:

views:

23

answers:

2

If you have two objects, ObjectA and ObjectB both inheriting from AbstractObject and a collection of AbstractObject. What would a linq statement look like where I select all objects in the collection of specific type. ex. something like:

var allBs = from b in collection where type == ObjectB select b;
+3  A: 

You can use Enumerable.OfType:

var allBs = collection.OfType<ObjectB>();

This gives you all elements where the type is castable to ObjectB. If you want objects which are only of type of ObjectB:

var allBs = collection.Select(i => i.GetType() == typeof(ObjectB));

or, alternatively:

var allBs = from b in collection 
            where b.GetType() == typeof(ObjectB) 
            select b;
Reed Copsey
+1  A: 

Very simple:

IEnumerable<ObjectB> allBs = collection.OfType<ObjectB>();

Or:

IEnumerable<AbstractObject> allBy = from b in collection
                                    where b is ObjectB
                                    select b;

The second query retains the same enumerable type as the collection, the first implicitly casts to IEnumerable<ObjectB>.

You could use these alternatives to cast the second query to IEnumerable<ObjectB>.

IEnumerable<ObjectB> allBs = (from b in collection
                              where b is ObjectB
                              select b).Cast<ObjectB>();

IEnumerable<ObjectB> allBs = from b in collection
                             where b is ObjectB
                             select b as ObjectB;
Enigmativity
That actually has a slightly different result than what the OP was asking for...
Reed Copsey
@"Reed Copsey" - I think the OP is a bit ambiguous as to whether it is all objects of a type including derived types or excluding derived types. Given that the code `b is ObjectB` returns true even when `b` is derived from `ObjectB` I went with the "included" meaning. Is that the point you were making?
Enigmativity