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 collecti开发者_JAVA技巧on where type == ObjectB select b;
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;
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;
精彩评论