简体   繁体   中英

C# Linq class searching - how to filter object collection

I would like to ask how to filter a particular class in an object collection using Linq?

Class1 c1 = new Class1();
Class2 c2 = new Class2();
List<object> c = new List<object>();
c.Add(c1);
c.Add(c1);
c.Add(c2);

I am searching for something like this:

c.Select();
// or
IEnumerable<object> x = from y in c;

Appreciate your response. Thank you so much.

c.OfType<Class1>() // returns an IEnumerable<Class1> with all instances of Class1 within C
c.OfType<Class2>() // same thing, but for Class2

Using the OfType<T> method, you can then use the remainder of the LINQ query filters on the strongly typed IEnumerable.

You can use OfType<T> for this.

var results = c.OfType<Class1>();

This

Console.WriteLine (c.OfType<Class1>().Count());

results in

2

As a sidenote: .Select() doesn't select anything. Well, in a way it does: it "selects" each element and projects it to a new object. But it doesn't select objects on some criterium. For values, there is .Where() and likewise selectors and .OfType<T> for the type selection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM