Merging two Datatables into One C# -
i have simple issue yet can't resolve , issue each time merge 2 datatables merge comes out funny looking , table 1 goes on top of table 2 , know because didn't set primary key of column ,but when did error because having duplicate values in enitity column .how pass , knowing duplicate values occur in primary key column
private void button1_click(object sender, eventargs e) { datatable merge = new datatable() ; merge.merge(t1()); merge.merge(t2()); gridcontrol1.datasource = merge.defaultview; } public datatable t1() { datacolumn col; datatable d = new datatable(); d.columns.add("enitity"); d.primarykey = new datacolumn[] { d.columns["enitity"] }; //d.primarykey = null; d.columns.add("variable"); d.rows.add(new string []{"k1","100"}); d.rows.add(new string[] { "k1", "200" }); d.rows.add(new string[] { "k3", "300" }); d.rows.add(new string[] { "k4", "400" }); d.rows.add(new string[] { "k6", "500" }); d.rows.add(new string[] { "k5", "600" }); return d; } public datatable t2() { datacolumn col; datatable d = new datatable(); d.columns.add("enitity"); d.primarykey = new datacolumn[] { d.columns["enitity"] }; d.primarykey = null; d.columns.add("variable2"); d.rows.add(new string[] { "k1", "1000" }); d.rows.add(new string[] { "k2", "2000" }); d.rows.add(new string[] { "k3", "3000" }); d.rows.add(new string[] { "k4", "4000" }); d.rows.add(new string[] { "k5", "5000" }); d.rows.add(new string[] { "k7", "6000" }); return d; }
this how merge looks
enitty variable variable 2 --------- ----- ----------- k1 . k2 . k3 . k4 . . . . k1 . k2 . k3 . k4 . . .
as stated above, cannot set primary key because have duplicate values. you're better off using linq, like:
datatable mynewdatatable = new datatable(); mynewdatatable.columns.add("enitity", typeof(string)); mynewdatatable.columns.add("variable", typeof(string)); mynewdatatable.columns.add("variable2", typeof(string)); var results = (from d1 in t1().asenumerable() join d2 in t2().asenumerable() on d1.field<string>("enitity") equals d2.field<string>("enitity") select mynewdatatable.loaddatarow( new object[] { d1.field<string>("enitity"), d1.field<string>("variable"), d2.field<string>("variable2") }, true) ); mynewdatatable = results.copytodatatable<datarow>();
Comments
Post a Comment