Thursday, 15 September 2011

c# - How to remove a column from datatable that is used in computed column? -



c# - How to remove a column from datatable that is used in computed column? -

i have datatable

fname lname tag1 tag2 tag3 ... (not fixed, can many)

what want

fname lname tagall

so, created column tagall of type string look

var look = string.empty; // ... other code // in loop tag columns look = look + " + ',' + " + tagcolumn; // @ end of loop dtcontact.columns["tag_all"].expression = expression;

so, if have 3 columns, look this

"tag1 + ',' + tag2 + ',' + tag3"

for illustration info is

fname lname tag1 tag2 tag3 jeff atwood test tag other matt breeden mytag total lastly

the resulting datatable becomes this

fname lname tag1 tag2 tag3 tag_all jeff atwood test tag other test, tag, other matt breeden mytag total lastly mytag, total, lastly

it fine till now, remove these other tag(s) column. tried doing

dtcontact.columns.removeat(2) throws 'system.argumentexception'

i guessing because column used in computed column expression, correct? because when remove column 0 or column 1. works fine. so, there way remove these other tag(s) column, given used in computed column expression? may somehow create column persistent? though searched on google couldn't find anything.

also, said, not fixed there 2, or 3 or n number of these tag(s) column, dynamic, , there can 1, tag1, upto any... tag88 or whatever.

try method:

//usage datatable dtmod = getmodifiedtable( dt); //function homecoming modified info table public datatable getmodifiedtable(datatable dt) { var columnlist = dt.columns.cast<datacolumn>() .where(x => x.columnname.startswith("tag")) .select(x => x.columnname) .toarray(); datatable dtnew = new datatable(); dtnew.columns.add("fname"); dtnew.columns.add("lname"); dtnew.columns.add("tag_all"); var results = dt.asenumerable().select(r => dtnew.loaddatarow( new object[] { r.field<string>("fname"), r.field<string>("lname"), gettagvalues(r, columnlist) }, false )); dtnew.rows.add(results.toarray()); homecoming dtnew; } //function homecoming csv values of given column list public string gettagvalues(datarow r, string[] columns ) { string csv = string.empty; foreach(string column in columns) { csv += r[column].tostring() + ","; } homecoming csv.substring(0, csv.length - 1); }

c# datatable

No comments:

Post a Comment