1

我有一个如下的数据表

    TableName   RowId   columnname  ColumnValue
    A           1       C1          V1
    A           1       C2          V2
    A           2       C1          V3
    A           2       C2          V4

我想转置到下面的结构

    TableName RowId C1 C2
    A         1     V1 V2
    A         2     V3 V4

如何在 C# 中做到这一点?

4

1 回答 1

2

我准备了一个有点复杂的解决方案,它不需要在ColumnNamesource 列中隐藏什么值DataTable

DataTable准备:

var source = new DataTable();
source.Columns.Add(new DataColumn("TableName", typeof(string)));
source.Columns.Add(new DataColumn("RowId", typeof(int)));
source.Columns.Add(new DataColumn("ColumnName", typeof(string)));
source.Columns.Add(new DataColumn("ColumnValue", typeof(string)));

source.Rows.Add("A", 1, "C1", "V1");
source.Rows.Add("A", 1, "C2", "V2");
source.Rows.Add("A", 2, "C1", "V3");
source.Rows.Add("A", 2, "C2", "V4");

目标DataTable准备:

var target = new DataTable();
target.Columns.Add(new DataColumn("TableName", typeof(string)));
target.Columns.Add(new DataColumn("RowId", typeof(int)));

帮助 LINQ 查询:

var query = from r in source.AsEnumerable()
            let i = new
            {
                TableName = r.Field<string>("TableName"),
                Id = r.Field<int>("RowId"),
                ColumnName = r.Field<string>("ColumnName"),
                ColumnValue = r.Field<string>("ColumnValue")
            }
            group i by new { i.TableName, i.Id } into g
            select g;

将数据插入target DataTable

foreach (var item in query)
{
    var newRow = target.NewRow();

    // static columns
    newRow["TableName"] = item.Key.TableName;
    newRow["RowId"] = item.Key.Id;

    // dynamic columns
    foreach (var c in item)
    {
        if(!target.Columns.Contains(c.ColumnName))
        {
            target.Columns.Add(new DataColumn(c.ColumnName, typeof(String)));
        }

        newRow[c.ColumnName] = c.ColumnValue;
    }

    target.Rows.Add(newRow);
}
于 2013-08-16T13:26:00.460 回答