Well, if the hierarchy is strictly 2 levels, you can always combine them and let LINQ sort SQL (this ends as one trip, although you need to see how fast it will work on your data volume):
var hlist = from h in Hierarchies select new {h.Parent, h.Child}; var slist = from h in Hierarchies join h2 in hlist on h.Parent equals h2.Child select new {h2.Parent, h.Child}; hlist = hlist.Union(slist);
This gives you a flat list of IEnumerable<{Item, Item}> , so if you want to group them, you just follow it:
var glist = from pc in hlist.AsEnumerable() group pc.Child by pc.Parent into g select new { Parent = g.Key, Children = g };
I used AsEnumerable() here when we reached the LINQ SQL provider capability with an attempt to group the Union. If you try it against IQueryable, it will launch a basic alliance for willing parents, then take a round-the-world trip for each parent (which you want to avoid). Regardless of whether you are suitable for using regular LINQ for grouping, you need the same amount of data to go through the channel anyway.
EDIT: Alternatively, you can create a view that binds the parent to all its children, and use this view as the basis for binding the elements. Theoretically, this should allow you / L 2S to group it with one trip.
source share