繁体   English   中英

使用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.

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