I have a class
public class Foo
{
public IList<Foo> Items { get; set; }
}
public class FooList
{
public IList<Foo> Items { get; set; }
}
I want to be able to get all of the Foo objects in one list, instead of a hierarchy.
I have tried
IEnumerable<Foo> result = Items.SelectMany(f => f.Items);
but this just gets me the items in that specific object – it doesn’t get all the items in all of the child objects.
I also tried
IEnumerable<Foo> result = Items.SelectMany(t => t)
But I get the error:
The type arguments for method ‘System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.
It’s fairly easy to knock together a “flatten-this-tree” LINQ-like function that you can use in the more general case:
Then if you have a
FooList, you can useto get all the
Foos in the list, along with all their children and all their children and…