我有三个类:Foo、Bar 和 Baz。 Bar 和 Baz 都扩展了抽象的 Foo。我有一个 Foo 类型的列表,里面充满了 Bars 和 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"));
当我这样做时,出现错误:附加信息:无法将类型为“WhereListIterator1[Foo]”的对象转换为类型“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();
关于c# - 使用 LINQ 获取特定子类型的列表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079059/