我准备了一个有点复杂的解决方案,它不需要在ColumnName
source 列中隐藏什么值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);
}