如何使用LINQ对数据表按Store和Item进行选择与分组?
如何使用LINQ按Store和Item对数据表行进行分组统计
需要对farmtable中的数据按Store和Item分组,统计每组的记录数量,最终输出包含Store、Item及对应分组的Count。
原始数据
| Id | Item | Store | Location |
|---|---|---|---|
| 1 | Apple | House A | Line-04 |
| 2 | Mango | House B | Line-23 |
| 1 | Apple | House A | Line-15 |
| 1 | Apple | House B | Line-08 |
| 3 | Banana | House A | Line-02 |
错误代码分析
你尝试的代码存在两个关键问题:
GroupBy(x => x.Store, x => x.Item)仅按Store单一字段分组,未同时包含Item,无法实现Store+Item的联合分组逻辑。Select中Item = group.Key赋值错误,此处group.Key是分组用的Store值,导致Item字段被错误覆盖为Store名称,数据结构完全不符合预期。
错误代码示例:
[HttpGet] public object Get() { return new { Items = _context.farmtable.GroupBy(x => x.Store, x => x.Item ) .Select(group => new { Store = group.Key, Item = group.Key, Items = group.ToList() }) .ToList(), Count = _context.farmtable.Count() }; }
正确的LINQ实现
要实现联合分组并统计数量,需将Store和Item作为联合分组键,再统计每组的记录数:
[HttpGet] public object Get() { var groupedData = _context.farmtable // 用匿名类型作为联合分组键,同时包含Store和Item .GroupBy(x => new { x.Store, x.Item }) // 提取分组键的字段,并统计每组记录数 .Select(group => new { Store = group.Key.Store, Item = group.Key.Item, Count = group.Count() }) .ToList(); return new { Items = groupedData, TotalCount = _context.farmtable.Count() }; }
执行结果
运行上述代码后,将得到符合预期的输出:
| Store | Item | Count |
|---|---|---|
| House A | Apple | 2 |
| House A | Banana | 1 |
| House B | Apple | 1 |
| House B | Mango | 1 |
内容的提问来源于stack exchange,提问作者Milie24
相关产品推荐
相关产品推荐

