Ale*_*lex 7 .net c# linq group-by
我正在尝试输出一些数据,分组,然后再次分组.
这是一些示例数据(来自db)

我正在尝试输出这个,分组如下:
Best Type Name
- Discipline name
-- Result
-- Result
-- Result
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
目前,我有以下内容
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()
};
Run Code Online (Sandbox Code Playgroud)
但这显然没有考虑到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>
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这就是你要找的东西:
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
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:
像这样迭代它:
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>
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4718 次 |
| 最近记录: |