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 to share