Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping / Multiple grouping with LINQ

I'm trying to output some data, grouped, then group it again.

Here's some example data (from db)

example data

I'm trying to output this, grouped like so:

Best Type Name
 - Discipline name
   -- Result  
   -- Result
   -- Result

CompetitorBest class looks like:

public class CompetitorBest
{
    public int ResultId { get; set; }
    public string BestTypeName { get; set; }
    public int BestTypeOrder { get; set; }
    public string DisciplineName { get; set; }
    public string ResultValue { get; set; }
    public string Venue { get; set; }
    public DateTime ResultDate { get; set; }
}

Currently, I've got the following

var bestsGroups = from b in Model.CompetitorBests
                  group b by new { b.BestTypeName, b.BestTypeOrder }
                  into grp
                  orderby grp.Key.BestTypeOrder
                  select new
                  {
                      BestType = grp.Key.BestTypeName,
                      Results = grp.ToList()
                  };

But this obviously doesn't take into account the grouping by DisciplineName.
My output code is something like:

foreach (var bestsGroup in bestsGroups)
{
    <h2>@bestsGroup.BestType</h2>

    foreach (var result in bestsGroup.Results)
    {
        //i am guessing here i'll need another foreach on the discipline group....
        <p>@result.DisciplineName</p>
        <p>@result.ResultId </p>
    }
}
like image 999
Alex Avatar asked Jul 05 '12 10:07

Alex


1 Answers

I think this is what you are looking for:

from b in Model.CompetitorBests
group b by new { b.BestTypeName, b.BestTypeOrder } into grp
orderby grp.Key.BestTypeOrder
select new
{
    BestType = grp.Key.BestTypeName,
    Results = from d in grp
              group d by d.DisciplineName into grp2
              select new
              {
                  DisciplineName = grp2.Key,
                  Results = grp2
              }
};

Edit:

Iterate over it like this:

foreach (var bestsGroup in bestsGroups)
{
    <h2>@bestsGroup.BestType</h2>

    foreach (var discipline in bestsGroup.Results)
    {
        <p>@discipline.DisciplineName</p>

        foreach (var result in discipline.Results)
        {
            <p>@result.ResultId</p>
        }
    }
}
like image 133
david.s Avatar answered Oct 18 '22 20:10

david.s