asp.net - Restructuring (transposing) datatable in c# -
i have datatable below
tablename rowid columnname columnvalue 1 c1 v1 1 c2 v2 2 c1 v3 2 c2 v4 i want transpose below structure
tablename rowid c1 c2 1 v1 v2 2 v3 v4 how in c#?
i prepared little complex solution, not require values hidden inside columnname column of source datatable:
source datatable preparation:
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"); target datatable preparation:
var target = new datatable(); target.columns.add(new datacolumn("tablename", typeof(string))); target.columns.add(new datacolumn("rowid", typeof(int))); helper linq query:
var query = r in source.asenumerable() let = new { tablename = r.field<string>("tablename"), id = r.field<int>("rowid"), columnname = r.field<string>("columnname"), columnvalue = r.field<string>("columnvalue") } group new { i.tablename, i.id } g select g; inserting data 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); }
Comments
Post a Comment