使用LINQ获取特定子类型的列表条目

Gam*_*ubi 3 c# linq collections ienumerable

我有三个班: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"));
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到一个错误:附加信息:无法转换'WhereListIterator 1[Foo]' to type 'System.Collections.Generic.List1 [Bar]' 类型的对象.

Dmi*_*nko 6

尝试OfType():过滤掉Bar项目并将它们具体化为列表:

List<Bar> bars = foos
  .OfType<Bar>()
  .ToList();
Run Code Online (Sandbox Code Playgroud)

编辑:如果您Bar只想要实例,但Baz即使Baz从何时派生,Bar您也必须添加条件:

List<Bar> bars = foos
  .OfType<Bar>()
  .Where(item => item.GetType() == typeof(Bar)) // Bar only
  .ToList();
Run Code Online (Sandbox Code Playgroud)