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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With