![](/img/trans.png)
[英]Get the objects with the maximum value for a specific property from a list using LINQ
[英]Get List entries of a specific subtype using LINQ
我有三個班:Foo,Bar和Baz。 Bar和Baz都擴展了Foo,這是抽象的。 我有一個類型Foo的列表,充滿了酒吧和Bazes。 我想使用LINQ Where子句返回所有類型。 就像是:
class Bar : Foo
{
public Bar()
{
}
}
class Baz : Foo
{
public Baz()
{
}
}
List<Foo> foos = new List<Foo>() { bar1, bar2, foo1, foo2, bar3 };
List<Bar> bars;
bars = (List<Bar>)foos.Where(o => o.GetType() == Type.GetType("Bar"));
當我這樣做時,我收到一個錯誤:附加信息:無法將'WhereListIterator 1[Foo]' to type 'System.Collections.Generic.List
對象強制1[Foo]' to type 'System.Collections.Generic.List
1 [Bar]'。
嘗試OfType() :過濾掉Bar
項並將它們實現到列表中:
List<Bar> bars = foos
.OfType<Bar>()
.ToList();
編輯:如果你只想要Bar
實例,而不是Baz
即使/當Baz
派生自Bar
你必須添加一個條件:
List<Bar> bars = foos
.OfType<Bar>()
.Where(item => item.GetType() == typeof(Bar)) // Bar only
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.