c# - 使用 LINQ 进行分组/多重分组

标签 c# .net linq group-by

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

这是一些示例数据(来自数据库)

example data

我正在尝试输出这个,像这样分组:

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

CompetitorBest 类看起来像:

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

最佳答案

我想这就是您要找的:

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

关于c# - 使用 LINQ 进行分组/多重分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11342781/

相关文章:

c# - ASP.Net 页面没有被编译

c# - 从字符串中获取数字和字符串

c# - FileStream WriteAsync 和 await 混淆

python - 适用于 Windows .NET 或 python 的视频编辑器桌面应用程序

c# - INotifyPropertyChanged - 为什么要进行额外的分配?

c# - 二维字典或查找表?

c# - Linq to Xml,是否可以改进此查询?

c# - 有什么方法可以使 yield created Iterator 在出现异常时继续到下一个项目?

c# - PredicateBuilder 的问题

c# - LINQ to Entities 不支持 LINQ 表达式节点类型 'ArrayIndex'