在c#中重构(转置)数据表

时间:2013-08-16 13:05:41

标签: c# asp.net datatable

我有一个像下面的数据

    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#中完成?

1 个答案:

答案 0 :(得分:2)

我准备了一个复杂的解决方案,它不需要在ColumnNameDataTable列的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))); 准备工作:

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;

Helper LINQ查询:

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); }

{{1}}