簡體   English   中英

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM