C#如何聚合两个数据行列表并在对应数据间添加分隔符?
解决方法
你原来的代码报错是因为DataRow对象不能直接用+运算符拼接,也没法直接把拼接结果转成DataTable。下面给两种实用的解决方案,按需选择:
方案1:把对应行的数据拼接成单一字符串列
适合只需要合并后文本的场景,生成只有一列的DataTable:
// 初始化结果表,添加存储拼接内容的列 DataTable dtCoreDivision = new DataTable(); dtCoreDivision.Columns.Add("合并后数据", typeof(string)); // 用Zip关联两个列表的对应行 foreach (var rowPair in tdListCoreAggregated.Data.AsEnumerable() .Zip(tdListDivisionAggregated.Data.AsEnumerable(), (coreRow, divRow) => new { coreRow, divRow })) { // 把每行的所有列值转成字符串(列之间用逗号分隔,可自行修改) string coreRowText = string.Join(", ", rowPair.coreRow.ItemArray.Select(item => item?.ToString() ?? "")); string divRowText = string.Join(", ", rowPair.divRow.ItemArray.Select(item => item?.ToString() ?? "")); // 用指定符号拼接两行内容 string combinedText = $"{coreRowText} | {divRowText}"; // 添加到结果表 dtCoreDivision.Rows.Add(combinedText); }
方案2:保留原列结构,合并两个表的列
如果需要保留原有数据的列结构,把两个表的列合并到新表中,还可以可选添加分隔符列:
// 复制核心列表的列结构作为基础 DataTable dtCoreDivision = tdListCoreAggregated.Data.Clone(); // 可选:添加分隔符列,默认值设为你需要的符号 dtCoreDivision.Columns.Add("分隔符", typeof(string)).DefaultValue = " | "; // 添加分部列表的列(给列名加前缀避免重复) foreach (DataColumn col in tdListDivisionAggregated.Data.Columns) { dtCoreDivision.Columns.Add($"分部_{col.ColumnName}", col.DataType); } // 遍历对应行,填充数据 foreach (var rowPair in tdListCoreAggregated.Data.AsEnumerable() .Zip(tdListDivisionAggregated.Data.AsEnumerable(), (coreRow, divRow) => new { coreRow, divRow })) { DataRow newRow = dtCoreDivision.NewRow(); // 复制核心行的所有数据 rowPair.coreRow.ItemArray.CopyTo(newRow.ItemArray, 0); // 复制分部行的数据(偏移量:核心列数 + 1(如果加了分隔符列)) int offset = tdListCoreAggregated.Data.Columns.Count + (dtCoreDivision.Columns.Contains("分隔符") ? 1 : 0); rowPair.divRow.ItemArray.CopyTo(newRow.ItemArray, offset); dtCoreDivision.Rows.Add(newRow); }
关键说明
Zip方法的用法是对的,它能精准关联两个序列的对应位置元素- 必须处理
DataRow的具体列值,不能直接操作DataRow对象本身进行拼接
内容的提问来源于stack exchange,提问作者Jana
相关产品推荐
相关产品推荐

