![](/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.