使用LINQ进行分组/多重分组

7

我正在尝试输出一些数据,首先按组分组,然后再次分组。

这是来自数据库的示例数据:

example data

我正在尝试以以下方式分组输出:

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

竞争者的最佳类别看起来像:

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; }
}

目前,我有以下内容:

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()
                  };

但这显然没有考虑按DisciplineName分组。
我的输出代码大致如下:
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>
    }
}
1个回答

8
我认为这就是你要找的内容:

我认为这是你在寻找的:

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
              }
};

编辑:

像这样迭代它:

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>
        }
    }
}

你有foreach的示例代码吗?我可以用它来迭代它吗? - Alex
1
@alexjamesbrown 我在答案中添加了一个示例。 - david.s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接