Query a for a specific type of object in the collection

If you have two objects, ObjectA and ObjectB, both inherit from AbstractObject and the AbstractObject collection. What would the linq operator look like when I select all the objects in a collection of a particular type. ex. sort of:

var allBs = from b in collection where type == ObjectB select b;
+3
source share
2 answers

You can use Enumerable.OfType :

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

This gives you all the elements in which a type can be hidden before ObjectB. If you want objects of type only 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;
+5
source

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 enumerated type as the collection, the first implicitly discards IEnumerable<ObjectB>.

, 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;
+2

Source: https://habr.com/ru/post/1763696/


All Articles