![](/img/trans.png)
[英]Best way to assign a value to a property of all objects in a collection using LINQ
[英]Best way to obtain objects from a collection that can be cast to a specific type using Linq
我正在尝试使用Linq获取更通用的实体集合中的所有Point对象。 请参考下面代码中的注释。 似乎.Cast()和.OfType()似乎没有满足我的要求。 代码是否是最佳选择?
// 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
结合了这两个操作:
return entityHost.Entities.OfType<Point>()
我认为
Entities.OfType<Point>
不起作用,因为Entities
的项目类型为IEntity
不,这是Entities
的声明类型。 OfType
查看每个项目的实际类型,如果“是” Point
则将其添加到结果中。 “ 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.