如何用LINQ实现分组聚合并将结果存入DataTable
嘿,这就帮你搞定用LINQ实现和那条SQL一样的分组聚合逻辑,还把结果存到指定的DataTable里~
需求回顾
原数据表rstable包含RSNo和Type两个字段,示例数据如下:
| RSNo | Type |
|---|---|
| Rs01 | 1 |
| Rs02 | 5 |
| Rs01 | 2 |
| Rs01 | 1 |
| Rs02 | 5 |
| Rs02 | 5 |
| Rs01 | 2 |
| Rs02 | 5 |
对应的SQL分组聚合语句是:
select rsno, type, count(type) as cnt from rstable group by rsno, type
执行后得到的结果:
| rsno | type | cnt |
|---|---|---|
| Rs01 | 1 | 2 |
| Rs01 | 2 | 2 |
| Rs02 | 5 | 4 |
LINQ实现方案
首先得确保目标DataTable dttypes的结构和结果匹配,然后通过LINQ完成分组聚合,最后把数据填充进去。下面是完整的代码实现:
// 假设原数据表已经加载为DataTable rstableDt DataTable dttypes = new DataTable(); // 先给目标DataTable添加对应字段,和结果结构一致 dttypes.Columns.Add("rsno", typeof(string)); dttypes.Columns.Add("type", typeof(int)); dttypes.Columns.Add("cnt", typeof(int)); // 使用LINQ进行分组聚合,逻辑和SQL完全对应 var groupedResult = from row in rstableDt.AsEnumerable() // 按RSNo和Type联合分组,对应SQL的group by rsno,type group row by new { RSNo = row.Field<string>("RSNo"), Type = row.Field<int>("Type") } into groupedRows // 提取分组键和统计数量,对应SQL的select rsno,type,count(type) as cnt select new { RsNo = groupedRows.Key.RSNo, Type = groupedRows.Key.Type, Cnt = groupedRows.Count() }; // 将LINQ查询结果逐行填充到dttypes中 foreach (var item in groupedResult) { DataRow newRow = dttypes.NewRow(); newRow["rsno"] = item.RsNo; newRow["type"] = item.Type; newRow["cnt"] = item.Cnt; dttypes.Rows.Add(newRow); }
关键细节说明
rstableDt.AsEnumerable():把DataTable转换成LINQ可操作的IEnumerable<DataRow>,这是LINQ操作DataTable的必备步骤。- 分组键用匿名类型:同时包含
RSNo和Type,保证分组逻辑和SQL的group by rsno,type完全一致。 groupedRows.Count():统计每个分组的行数,和SQL里的count(type)效果相同(因为每个分组里的行都有对应的Type值)。
内容的提问来源于stack exchange,提问作者Priya
相关产品推荐
相关产品推荐

