R Jack
R Jack

Reputation: 31

Query a for a specific object type in a collection

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;

Upvotes: 3

Views: 1063

Answers (2)

Enigmativity
Enigmativity

Reputation: 117074

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;

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564433

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;

Upvotes: 5

Related Questions