[英]Best way to obtain objects from a collection that can be cast to a specific type using Linq
I'm trying to obtain all the Point objects in the a more general collection of Entities using Linq. 我正在尝试使用Linq获取更通用的实体集合中的所有Point对象。 Please refer to the comments in the code below.
请参考下面代码中的注释。 It appears that .Cast() and .OfType() do not seem to do what I need.
似乎.Cast()和.OfType()似乎没有满足我的要求。 Is the code below the best option?
代码是否是最佳选择?
// IHost has an Entities collection that contains different types of entities that implement IEntity, and one of specific types may be a Point object.
public System.Linq.ParallelQuery<Point> GetPoints(IHost entityHost)
{
// Is this the best way to get a collection of Points from the Entities, using Linq?
// I believe Entities.OfType<Point> does not work because the type of item in Entities is IEntity
// I believe Entities.Cast<Point> does not work because there will be exceptions due to non-Point objects in the collection
return entityHost.Entities.Where(o => o is Point).Cast<Point>();
}
OfType
combines those two operations: OfType
结合了这两个操作:
return entityHost.Entities.OfType<Point>()
I believe
Entities.OfType<Point>
does not work because the type of item inEntities
isIEntity
我认为
Entities.OfType<Point>
不起作用,因为Entities
的项目类型为IEntity
No, that's the declared type of Entities
. 不,这是
Entities
的声明类型。 OfType
looks at the actual type of each item, and adds it to the result if it "is" a Point
. OfType
查看每个项目的实际类型,如果“是” Point
则将其添加到结果中。 By "is" I mean "can be cast to" - literally using the is
operator : “ is”是指“可以强制转换为”-实际上使用
is
运算符 :
static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)
{
foreach (object obj in source) {
if (obj is TResult) yield return (TResult)obj;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.