ThomasG
ThomasG

Reputation: 129

How to group a list of lists into repeated items

I have a C# problem. I have a list of object of Type Item. I need to group the sub item lists of all of these both "subItemCode", as this can be repeated between items, and by "subItemGroup", which can also be repeated. I have the idea I'll want to do some LINQ grouping, but unsure what to group by?

class Item
{
   string itemCode;
   List<SubItem> subItems;
}

class SubItem
{
  string subItemCode;
  string subItemGroup;
  List<string> validParentItems;
}

So, my idea would be to do something like

 var results = from item in ItemList
               from subItem in item.subItems
               group subItem by ???????

So, any pointer at how I can group my items?

Note: Before anyone says, not homework. Just don't see the point in tearing my hair out over it when I could be getting on with something more productive. No point re-inventing the wheel right?

Upvotes: 1

Views: 266

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460128

Perhaps

var results = ItemList
   .GroupBy(i => i.itemCode)
   .Select(g => new{ 
       itemcode = g.Key, 
       subItemGroups = g
          .SelectMany(i => i.subItems)
          .GroupBy(si => si.subItemGroup)
   });

Output:

foreach (var grp in results)
{
    string groupCode = grp.itemcode;
    foreach (var subGrp in grp.subItemGroups)
    {
        string subItemGroup = subGrp.Key;
        Console.WriteLine("groupCode:{0} subItemGroup:{1} codes:{2}"
            , groupCode
            , subItemGroup
            , String.Join(",", subGrp.Select(si => si.subItemCode)));
    }
}

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

By selecting new { item, subItem } in your group, you can include both the item and subItem in your results. You can group by the code, or the group, but I don't understand how you might want to group by both, as you seem to say. Here's code to group by both as separate statements:

var resultsByCode = from item in ItemList
                    from subItem in item.subItems
                    group new { item, subItem } by subItem.subItemCode;
var resultsByGroup = from item in ItemList
                     from subItem in item.subItems
                     group new { item, subItem } by subItem.subItemGroup;

Upvotes: 0

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

Try this:

var results = ItemList.SelectMany(i => i.subItems).GroupBy(i => i.subItemGroup);

Upvotes: 3

Related Questions