c# - How to select first n number of columns from a DataTable -
i have datatable containing dynamic number of rows , dynamic number of columns,
col1 col2 col3 col4............coln ________________________________________________________________________ row1col1 row1col2 row1col3 row1col4........row1coln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rowncol1 rowncol2 rowncol3 rowncol4.......rowncoln
how select data first n number of columns datatable?
to columns:
var tbl = new system.data.datatable(); var cols = tbl.columns.cast<system.data.datacolumn>().take(20);
// if wish first 20 columns...
if want data, have loop through columns data.
var data = cols.selectmany(x => tbl.rows.cast().take(100).select(y => y[x]));
of course, dump data ienumerable, if want use strong typed object or list of 1 dimensional array, believe it's simple, example:
var data2 = cols.select(x => tbl.rows.cast().take(100).select(y => y[x]).toarray());
if wish keep current table , reserve number of columns/rows, can remove rest columns/rows:
var tbl = new system.data.datatable(); int totalcolumnstoreserve = 20; (int = tbl.columns.count - 1; >= totalcolumnstoreserve; i--) { tbl.columns.removeat(i); } int totalrowstoreserve = 100; (int = tbl.rows.count - 1; >= totalrowstoreserve; i--) { tbl.rows.removeat(i); }
Comments
Post a Comment