簡體   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