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

如何使用C# LINQ对DataRow分组并拼接多列数据?

解决LINQ分组拼接DataTable的CS1929错误并实现需求

错误原因

CS1929错误的核心是:你直接在IGrouping<string, DataRow>类型的分组对象g上调用了Field方法,但Field是单个DataRow的扩展方法,分组对象是一组DataRow的集合,并非单个行,因此无法直接调用。

解决方案

要实现按ProductID分组并拼接其他列的需求,需要遍历分组内的每一行提取字段值,再用string.Join拼接成分号分隔的字符串。以下是完整实现代码:

1. 分组拼接得到匿名类型集合

DataTable dt = ProcessData(); // 你的原始DataTable

var groupedData = dt.AsEnumerable()
    // 按ProductID分组,注意字段类型:示例中ProductID是整数,若实际为字符串则改为Field<string>
    .GroupBy(row => row.Field<int>("ProductID"))
    .Select(group => new
    {
        ProductID = group.Key,
        // 拼接CustomerID,转换为字符串后用分号连接
        CustomerID = string.Join(";", group.Select(row => row.Field<int>("CustomerID"))),
        // 拼接CustomerState,处理可能的null值
        CustomerState = string.Join(";", group.Select(row => row.Field<string>("CustomerState") ?? string.Empty)),
        // 拼接CustomerCity,处理可能的null值
        CustomerCity = string.Join(";", group.Select(row => row.Field<string>("CustomerCity") ?? string.Empty))
    });

2. 转换回DataTable(可选)

如果需要将结果转回DataTable格式,可添加以下代码:

DataTable resultTable = new DataTable("GroupedProducts");
// 定义结果表列结构
resultTable.Columns.Add("ProductID", typeof(int));
resultTable.Columns.Add("CustomerID", typeof(string));
resultTable.Columns.Add("CustomerState", typeof(string));
resultTable.Columns.Add("CustomerCity", typeof(string));

// 将分组数据填入结果表
foreach (var item in groupedData)
{
    resultTable.Rows.Add(item.ProductID, item.CustomerID, item.CustomerState, item.CustomerCity);
}

效果验证

运行后得到的结果与你需求的表格完全一致:

ProductIDCustomerIDCustomerStateCustomerCity
11TXAustin
22;3;4AZ;OK;COPhoenix;Oklahoma;Denver
31TXAustin

内容的提问来源于stack exchange,提问作者Massey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:37:02