Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List entries of a specific subtype using LINQ

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.List1[Bar]'.

like image 512
GameKyuubi Avatar asked Mar 11 '23 11:03

GameKyuubi


1 Answers

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();
like image 79
Dmitry Bychenko Avatar answered Mar 20 '23 08:03

Dmitry Bychenko