Oliver
Oliver

Reputation: 45071

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

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?

Upvotes: 1

Views: 5795

Answers (2)

Saurabh
Saurabh

Reputation: 47

You can use the following code to get a similar output-

var result = Table.AsEnumerable().Select(row => 
             new { 
                   FirstName = row.ItemArray[Table.Columns["FirstName"].Ordinal], 
                   LastName = row.ItemArray[Table.Columns["LastName"].Ordinal] 
                 });

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292385

You don't need Linq to do that :

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

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

Upvotes: 3

Related Questions