You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用LINQ实现分组聚合并将结果存入DataTable

嘿,这就帮你搞定用LINQ实现和那条SQL一样的分组聚合逻辑,还把结果存到指定的DataTable里~

需求回顾

原数据表rstable包含RSNo和Type两个字段,示例数据如下:

RSNoType
Rs011
Rs025
Rs012
Rs011
Rs025
Rs025
Rs012
Rs025

对应的SQL分组聚合语句是:

select rsno, type, count(type) as cnt from rstable group by rsno, type

执行后得到的结果:

rsnotypecnt
Rs0112
Rs0122
Rs0254
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:57