bar.Foos.Where(x => x.Definition.Parent == null) .Select(x => Tuple.Create(x, bar.Foos.Where(c => c.Definition .Parent == x.Definition )));
This will return IEnumerable<Tuple<Foo, IEnumerable<Foo>>> , where Item2 from Tuple contains children for the parent in Item1 . For your example, this returns two sets:
Item1 = simpleDefinition and Item2 containing an empty enumeratedItem1 = parentDefinition and Item2 containing an enumerated containing childDefinition
There may be a more elegant or faster way, but I could not come up with it ...
Well, I was a bit contrary to my own comment, but this is possible with GroupBy - at least almost:
bar.Foos.Where(x => x.Definition.Parent == null) .GroupBy(x => x, x => bar.Foos.Where(c => c.Definition.Parent == x.Definition));
This will return IEnumerable<IGrouping<Foo, IEnumerable<Foo>>> .
Update:
I wanted to know if the solution you wanted was possible at all. Yes it:
bar.Foos.Where(x => x.Definition.Parent != null) .GroupBy(x => bar.Foos.Where(y => y.Definition == x.Definition.Parent) .Single(), x => x) .Union(bar.Foos.Where(x => x.Definition.Parent == null && !bar.Foos.Any(c => c.Definition.Parent == x.Definition)) .GroupBy(x => x, x => (Foo)null));
But I really do not want to know big O of this, and it really should not be used; -)
source share