c# - Adding Data to existing DataTable's DataRow -
i want add data existing datarow in datatable. idea is, without copying data exists.
when writing tests, found out directly inserting data slower copying both existing data , new new row , add row.
or doing wrong?
first create datatable initial data.
fill initial data:
datatable table1 = new datatable(); int count = 15; (int = 0; < count; i++) { table1.columns.add("hallo" + i, % 2 == 0 ? typeof(int) : typeof(string)); } int newstartindex = table1.columns.count; datetime pre = datetime.now; (int = 0; < 100000; i++) { datarow row = table1.newrow(); (int j = 0; j < table1.columns.count; j++) { if (j % 2 == 0) { row[j] = 502; } else { row[j] = "test"; } } table1.rows.add(row); }
afterwards add 15 columns , data.
for (int = count; < 2 * count; i++) { table1.columns.add("hallo" + i, % 2 == 0 ? typeof(int) : typeof(string)); } foreach( datarow row in table1.rows) { (int j = newstartindex; j < table1.columns.count; j++) { if (j % 2 == 0) { row[j] = 502; } else { row[j] = "test"; } } }
when taking time, shows inserting data (which should same data data added) takes 10 times long initial filling.
now tried same copying data:
list<object[]> toadd = new list<object[]>(); foreach (datarow row in table1.rows) { object[] newarray = new object[table1.columns.count]; array.copy(row.itemarray, newarray, count); (int j = newstartindex; j < table1.columns.count; j++) { if (j % 2 == 0) { newarray[j] = 502; } else { newarray[j] = "test"; } } toadd.add(newarray); } table1.rows.clear(); foreach( var o in toadd) { table1.rows.add(o); }
this takes 2.5 times long initial filling, makes lot faster directly inserting.
somehow think there must faster way add data copy , add anew.
i tried writing datarow.itemarray, changes not present in datatable after writing there.
any ideas? , maybe explanations behavior?
i'm not sure why going through such efforts, , have own reasons.
not exact syntax, however, have looked things like...
datatable.clone() // make copy datatable.merge() // merge 1 datatable rows (w/matching columns) dataview odv = yourdatatable.defaultview odv.filter = ... datatable newtable = odv.totable()
Comments
Post a Comment