joacoleza
joacoleza

Reputation: 825

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 of class1, but I want to get only the ones of type class2, something like:

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

how is the proper way of doing this?

Thanks!

Upvotes: 3

Views: 145

Answers (2)

Iain Galloway
Iain Galloway

Reputation: 19230

You probably want OfType<T>():-

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

As well as being more succinct, this has the added benefit that newList is of type List<Class2> (rather than being a List<Class1> which happens to contain only instances of Class2) saving you casting further down the line.

Upvotes: 9

DLeh
DLeh

Reputation: 24405

You want to use the GetType() method and typeof():

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

Or, you can use is:

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

Upvotes: 2

Related Questions