Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Nested Grouping in Linq

Suppose, for example, in my C# code, I have MyClass, defined as:

public class MyClass
{
    public string GroupName;
    public DateTime Dt;
    .... other properties ....
}

And suppose I had the following List<MyClass> (showing it as a table since it seems the easiest way to describe the contents):

GroupName:       Dt:             Val:
Group1           2016/01/01      a
Group1           2016/01/02      b
Group1           2016/01/03      c
Group2           2016/01/01      d
Group2           2016/01/02      e
Group3           2016/01/01      f
Group3           2016/01/02      g
Group3           2016/01/03      h

And I'm looking to get from this list all the data:

  1. Firstly grouped by Dt
  2. Secondly grouped by GroupName

So, (and I'm sure this is wrong, but I'm hoping it'll explain what I'm looking for), I'd like to get an IEnumerable<IGrouping<DateTime, IEnumerable<IGrouping<string, IEnumerable<MyClass>>>>

My best attempt at managing to get this was the following:

return MyList
    .GroupBy(d => d.Dt)
    .GroupBy(grp => grp.ToList().GroupBy(d => d.GroupName));

I know this is wrong, but this is the only thing I could figure out. How could I get what I'm looking for?

like image 341
John Bustos Avatar asked Dec 24 '22 07:12

John Bustos


1 Answers

Use Select:

return MyList
    .GroupBy(d => d.Dt)
    .Select(grp => grp.GroupBy(d => d.GroupName));

To get exactly what you want you'd need an extra GroupBy after the Select:

var groups = MyList
    .GroupBy(d => d.Dt)
    .Select(grp => new { key = grp.Key, items = grp.GroupBy(d => d.GroupName) })
    .GroupBy(grp => grp.key, grp => grp.items);

enter image description here

like image 124
MarcinJuraszek Avatar answered Dec 28 '22 08:12

MarcinJuraszek