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:
Dt
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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With