Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ selection by type of an object

Tags:

c#

linq

c#-3.0

I have a collection which contains two type of objects A & B.

Class Base{} Class A : Base {} Class B : Base {}  List<Base> collection = new List<Base>(); collection.Add(new A()); collection.Add(new B()); collection.Add(new A()); collection.Add(new A()); collection.Add(new B()); 

Now I want to select the objects from the collection based on its type (A or B, not both).

How I can write a LINQ query for this? Otherwise I need to loop through the collection, which I don't want to.

Edit:

Thank you all for your help. Now I can use OfType() from LINQ. But I think in my case it won't work. My situation is

Class Container {   List<Base> bases; }  List<Container> containers = new List<Container>(); 

Now I want to select the container from containers, which has at least one type A. Maybe this can't be done by LINQ.

like image 959
jaks Avatar asked Oct 01 '10 20:10

jaks


People also ask

Does LINQ Select return new object?

While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.

What a LINQ query returns in LINQ to object?

Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

How do I Select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.


1 Answers

You can use the OfType Linq method for that:

var ofTypeA = collection.OfType<A>(); 

Regarding your unwillingness to loop throught the collection, you should keep in mind that Linq does not do magic tricks; I didn't check the implementation of OfType, but I would be surprised not to find a loop or iterator in there.

like image 139
Fredrik Mörk Avatar answered Sep 22 '22 10:09

Fredrik Mörk