[英]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? 如何在这里过滤这些对象?
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.