c# - DataTable remove columns and re-order the columns -


i want remove unwanted columns datatable , arrange order of columns in pre-defined order

for example, table columns below,

 col2|col1|col3|test|test1|col5|col4|some col name|col6 

i want remove test, test1 , col name , reorder datatable below format

col1|col2|col3|col4|col5|col6  // need below columns list<string> tablecolumns = new list<string>(); tablecolumns.add("col1"); tablecolumns.add("col2"); tablecolumns.add("col3"); tablecolumns.add("col4"); tablecolumns.add("col5"); tablecolumns.add("col6");  list<datacolumn> tblcolumns = mydatatable.columns.cast<datacolumn>().tolist();  //remove unwanted columns foreach (datacolumn col in tblcolumns) {   if (!tablecolumns.contains(col.columnname.trim()))   {    mydatatable.columns.remove(col);   } } 

now how re-order columns in below order?

col1|col2|col3|col4|col5|col6 

i tried in below code, fails if items in tablecolumns doesn’t exists in datatable. times data table column name has empty space (ex “ col1”)

foreach (var col in tablecolumns) {       mydatatable.columns[col].setordinal(tablecolumns.indexof(col));  } 

which best way remove unwanted columns , re-arrange columns?

after remove unwanted columns, here how can order them:

int index = 0;  foreach (var col in     mydatatable.columns     .cast<datacolumn>()     .orderby(x => tablecolumns.indexof(x.columnname))     .tolist()) {     col.setordinal(index);     index ++; } 

this selects columns datatable, , orders them corresponding index in tablecolumns list.

then invokes setordinal on each 1 of them, incrementing index each time.


Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -