Reputation: 45071
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:
| ID | FirstName | LastName | Age |
+----+-----------+----------+-----+
| 1 | Alice | Wannabe | 22 |
| 2 | Bob | Consumer | 27 |
| 3 | Carol | Detector | 25 |
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
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
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