How to get all rows but specifc columns from a DataTable?

Posted by Oliver on Stack Overflow See other posts from Stack Overflow or by Oliver
Published on 2010-03-08T10:11:59Z Indexed on 2010/03/08 10:51 UTC
Read the original article Hit count: 439

Filed under:
|
|

Currently i am having some problems with getting some data out of a DataTable by selecting all rows, but only some columns.

To be a little more descriptive here is a little example:

Sample Data

| ID | FirstName | LastName | Age |
+----+-----------+----------+-----+
|  1 | Alice     | Wannabe  | 22  |
|  2 | Bob       | Consumer | 27  |
|  3 | Carol     | Detector | 25  |

What i have

So what we got from our GUI is a IEnumerable<DataColumn> selectedColumns and there we'll find two elements (FirstName and LastName).

Now i need some result which contains all rows, but only the above two columns (or any other list of selected columns).

So far i already used LINQ on several one dimensional objects, but this two dimensional object gives me a little headache.

// The hard-coded way
Table.AsEnumerable().Select(row => new { FirstName = row[1], LastName = row[2] });

// The flexible way
Table.AsEnumerable().Select(row => row ???)

But how can i now say, which columns from row should be selected by using my selectedColumns?

© Stack Overflow or respective owner

Related posts about c#

Related posts about datatable