简体   繁体   English

LINQ按类类型过滤

[英]linq filtering by class type

I have a list contains 2 different types of objects which are polylines and texts. 我有一个列表,其中包含2种不同类型的对象,即折线和文本。 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. 错误:“ PolyLine”是一种类型,在给定的上下文中无效。

How do I filter those objects here? 如何在这里过滤这些对象?

Simply use the OfType<T> extension: 只需使用OfType<T>扩展名:

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

This selects all elements in list1 that are of type PolyLine . 这将选择list1中类型为PolyLine所有元素。

After ToList() the resulting type of list2 is List<PolyLine> . ToList()之后, list2的结果类型为List<PolyLine>

You don't need a SelectMany rather you need a Where clause: 您不需要SelectMany而是需要Where子句:

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

This uses the is operator to get the correct type. 这使用is运算符来获取正确的类型。

This could further be simplified with the use of OfType extension method. 使用OfType扩展方法可以进一步简化此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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