I have three classes: Foo, Bar, and Baz. Bar and Baz both extend Foo, which is abstract. I have a List of type Foo, filled with Bars and Bazes. I want to use a LINQ Where clause to return all of one type. Something like:
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"));
When I do this I get an error: Additional information: Unable to cast object of type 'WhereListIterator1[Foo]' to type 'System.Collections.Generic.List
1[Bar]'.
Try OfType(): filter out Bar
items and materialize them into list:
List<Bar> bars = foos
.OfType<Bar>()
.ToList();
Edit: If you want Bar
instances only, but not Baz
even if/when Baz
is derived from Bar
you have to add a condition:
List<Bar> bars = foos
.OfType<Bar>()
.Where(item => item.GetType() == typeof(Bar)) // Bar only
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With