按数据组分组并组合数据

时间:2017-09-12 08:26:39

标签: c# datatable

我有这样的数据表。 enter image description here

如果Datacolumn“Dept。”和“部分”是相同的。 我想结合数据。

像这样。

enter image description here

怎么做?

我试试:

var temp = (from x in workTable.AsEnumerable()
               group x by new
             {
            DepartmentID = x.Field<string>("DepartmentID"),
                                     SectionID = x.Field<string>("SectionID")
                                 } into g
                                 select g  
                                 ).ToList();

1 个答案:

答案 0 :(得分:1)

您可以使用以下循环来合并这些行:

var depSectGroups = workTable.AsEnumerable()
    .GroupBy(row => new {DepartmentID = row.Field<string>("DepartmentID"), SectionID = row.Field<string>("SectionID")});

DataTable resultTable = workTable.Clone();
foreach (var rowGroup in depSectGroups)
{
    if (rowGroup.Count() == 1)
        resultTable.ImportRow(rowGroup.First());
    else
    {
        DataRow addedRow = resultTable.Rows.Add();
        foreach (DataRow row in rowGroup)
        {
            foreach (DataColumn col in row.Table.Columns)
            {
                if (addedRow.IsNull(col.ColumnName) && !row.IsNull(col))
                    addedRow[col.ColumnName] = row[col];
            }
        }
    }
}