linq filtering by class type

Viewed 1344

I have a list contains 2 different types of objects which are polylines and texts. I want to create a new list of polylines only.

what I do is;

var list2 = list1.SelectMany(x=> x.Type == PolyLine)

Error:'PolyLine' is a type, which is not valid in the given context.

How do I filter those objects here?

2 Answers

Simply use the OfType<T> extension:

var list2 = list1.OfType<PolyLine>().ToList();

This selects all elements in list1 that are of type PolyLine.

After ToList() the resulting type of list2 is List<PolyLine>.

You don't need a SelectMany rather you need a Where clause:

var result = list1.Where(x => x is PolyLine);

This uses the is operator to get the correct type.

This could further be simplified with the use of OfType extension method.

Related