tags:

views:

127

answers:

1

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?

+1  A: 

You don't need Linq to do that :

string[] selectedColumns = new[] { "ID", "LastName" };

DataTable tableWithOnlySelectedColumns =
    new DataView(table).ToTable(false, selectedColumns);
Thomas Levesque