How do I filter a collection by type?

I have three classes:

public class class1 {}
public class class2 : class1 {}
public class class3 : class1 {}

      

and a list of items class1

, but I only want to get those that are of type class2

, something like:

list = list.where(x=>x.classType == class2)

      

how to do it correctly?

Thank!

+3


source to share


2 answers


You probably want OfType<T>()

: -

var newList = list.OfType<Class2>().ToList();

      



Also, it has the added benefit of being newList

type List<Class2>

(rather than like List<Class1>

, which only contains instances Class2

), which allows you to dump you further down the line.

+9


source


You want to use a method GetType()

and typeof()

:

list = list.Where(x => x.GetType() == typeof(class2)).ToList(); 

      



Or you can use is

:

list = list.Where(x => x is class2).ToList();

      

+2


source







All Articles