Grouping nested objects using List(T).GroupBy()
c#, linq
Solution
Well, what data type are you expecting to get back? Currently, it'll be `IGrouping<Category, Item>` but if you want the topmost category to be the key, then the values could presumably be items or categories.
You've shown the results as XML, but how are you actually going to use them? Given the results you've got, can't you easily get the parent category anyway? Do you need to use the parent category in the actual grouping part? If two categories have the same parent category, do you want all the items in that parent category to be mashed together?
Sorry for all the questions - but the more we know, the better we'll be able to help you.
EDIT: If you just want to group items by the topmost category, you can do
items.GroupBy(x => GetTopmostCategory(x))
...
public Category GetTopmostCategory(Item item)
{
Category category = item.Category;
while (category.Parent != null)
{
category = category.Parent;
}
return category;
}
(You could put this into `Category` or `Item`, potentially.) That would give you exactly the same return type, but the grouping would just be via the topmost category. Hope this is actually what you want...
Problem
I have an odd sorting case I'm struggling to work out using LINQs GroupBy method. I have two classes: Category and Item. Every Item has a category, and a Category can have a parent Category. What I need to do is organize all of the Items by their proper Category, but I also want to sort the Categories by the parent Category if there is one. So ideally I should be able to visualize my results like: ``` <Category 1> <Item 1> <Item 2> </Category 1> <Category 2> <Category 3> <Item 3> <Item 4> </Category 3> </Category 2> <Category 4> <Item 5> </Category 4> <Category 5> <Item 6> </Category 5> ``` I'm currently using `items.GroupBy(x => x.Category)` which gives me everything except the parent categories. So my results look like: ``` <Category 1> <Item 1> <Item 2> </Category 1> <Category 3> <Item 3> <Item 4> </Category 3> <Category 4> <Item 5> </Category 4> <Category 5> <Item 6> </Category 5> ``` The issue being that (in this example) the parent category for Category 3 (Category 2) isn't listed. I started goofing around with nested groups, but I didn't get very far before considering just manually walking the tree myself (foreach'ing). Before I do that, I'm hoping the LINQ gurus here can help me out...