我正在尝试使用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>();
}
答案 0 :(得分:5)
OfType
结合了这两项操作:
return entityHost.Entities.OfType<Point>()
我认为
Entities.OfType<Point>
不起作用,因为Entities
中的项目类型为IEntity
不,那是声明的类型Entities
。 OfType
查看每个项目的实际类型,如果&#34;是&#34;则将其添加到结果中。一个Point
。 &#34;是&#34;&#34;我的意思是&#34;可以演绎到&#34; - 字面意思using the is
operator:
static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)
{
foreach (object obj in source) {
if (obj is TResult) yield return (TResult)obj;
}
}