如何用单条LINQ查询实现嵌套分组并生成指定GroupModel列表?
用单条LINQ查询生成指定结构的List
问题背景
现有如下数据表格:
| date | Type | Agency | TotalCount | ABC_Count | DEF_Count | GHI_Count |
|---|---|---|---|---|---|---|
| JAN-2022 | X | B2X | 5 | 5 | 2 | 3 |
| JAN-2022 | X | C4A | 7 | 5 | 7 | 2 |
| FEB-2022 | X | B2X | 3 | 2 | 3 | 1 |
| FEB-2022 | X | C4A | 9 | 1 | 9 | 4 |
| MAR-2022 | X | B2X | 8 | 3 | 1 | 8 |
| MAR-2022 | X | C4A | 7 | 1 | 1 | 7 |
| JAN-2022 | Y | D5Y | 6 | 6 | 4 | 3 |
| JAN-2022 | Y | E7T | 7 | 3 | 7 | 2 |
| FEB-2022 | Y | D5Y | 4 | 2 | 4 | 1 |
| FEB-2022 | Y | E7T | 9 | 2 | 9 | 4 |
| MAR-2022 | Y | D5Y | 8 | 3 | 1 | 8 |
| MAR-2022 | Y | E7T | 8 | 1 | 1 | 8 |
已定义C#模型类:
public class GroupModel { public string LetterGroupName { get; set; } public List<LetterGroupData> LetterGroupData { get; set; } } public class LetterGroupData { public string Date { get; set; } public double TypeX_Ave { get; set; } public double TypeY_Ave { get; set; } public int Total { get; set; } }
需要生成List<GroupModel>类型结果集,各字段计算规则:
Total:对应日期下Type X和Y的TotalCount总和TypeX_Ave:(对应日期下Type X的目标Count字段总和 / 该日期Total)*100TypeY_Ave:(对应日期下Type Y的目标Count字段总和 / 该日期Total)*100- 需按ABC、DEF、GHI三个分组分别统计
解决方案
可以通过单条LINQ查询实现,核心思路是先按日期聚合计算总TotalCount,再针对每个字母分组(ABC/DEF/GHI),结合日期维度计算对应平均值:
var result = new[] { "ABC", "DEF", "GHI" } .Select(groupName => new GroupModel { LetterGroupName = groupName, LetterGroupData = dt.AsEnumerable() .GroupBy(row => row.Field<string>("date")) .Select(dateGroup => { var total = dateGroup.Sum(row => row.Field<int>("TotalCount")); var typeXSum = dateGroup.Where(row => row.Field<string>("Type") == "X") .Sum(row => row.Field<int>($"{groupName}_Count")); var typeYSum = dateGroup.Where(row => row.Field<string>("Type") == "Y") .Sum(row => row.Field<int>($"{groupName}_Count")); return new LetterGroupData { Date = dateGroup.Key, Total = total, TypeX_Ave = total == 0 ? 0 : Math.Round((double)typeXSum / total * 100, 1), TypeY_Ave = total == 0 ? 0 : Math.Round((double)typeYSum / total * 100, 1) }; }) .OrderBy(data => data.Date) .ToList() }) .ToList();
代码说明
- 先枚举三个目标分组(ABC/DEF/GHI),逐个构建
GroupModel - 对每个分组,将DataTable行按日期分组:
- 计算该日期下所有Type的TotalCount总和
total - 分别统计Type X和Y对应分组Count字段的总和
- 按公式计算平均值,处理除数为0的边界情况,保留一位小数(可按需调整)
- 计算该日期下所有Type的TotalCount总和
- 按日期排序后封装为
LetterGroupData列表,最终组合成List<GroupModel>
内容的提问来源于stack exchange,提问作者ricksley
相关产品推荐
相关产品推荐

