Let’s say I have this simple structure
class FooDefinition
{
public FooDefinition Parent { get; set; }
}
class Foo
{
public FooDefinition Definition { get; set; }
}
class Bar
{
public ICollection<Foo> Foos { get; set; }
}
A Bar has a list of Foos which can be simple (no parent/child relationships) or nested just one level (i.e. a parent Foo has many child Foos). As can be seen here, the relationships are specified in the FooDefinition, not the Foo itself.
What I need to do is generate a list of Foos properly grouped by this hierarchy. Consider the following source data:
var simpleDefinition = new FooDefinition();
var parentDefinition = new FooDefinition();
var childDefinition = new FooDefinition { Parent = parentDefinition };
var bar = new Bar { Foos = new[]
{
new Foo { Definition = simpleDefinition },
new Foo { Definition = parentDefinition },
new Foo { Definition = childDefinition }
}};
I’d like to get a collection of top-level items with their chilren. An adequate data structure would probably be IEnumerable<IGrouping<Foo, Foo>>.
The result would look like:
- Item 1 (simple)
- Item 2 (parent)
- Item 3 (child)
And of course I’d like to do this with a purely-functional Linq query. I do lots of these, but my brain seems to be stuck today.
This will return an
IEnumerable<Tuple<Foo, IEnumerable<Foo>>>, whereItem2of theTuplecontains the children for the parent inItem1. For your example, this returns two Tuples:Item1 = simpleDefinitionandItem2containing an empty enumerableItem1 = parentDefinitionandItem2containing an enumerable which containschildDefinitionThere might be a more elegant or faster way, but I couldn’t come up with it…
Oh well, I contradict my own comment a little bit with this, but it is possible with
GroupBy– at least nearly:This will return an
IEnumerable<IGrouping<Foo, IEnumerable<Foo>>>.Update:
I wanted to know, if the solution you wanted is possible at all.
Yes, it is:
But I really don’t want to know the big O of this and it really shouldn’t be used 😉