Reputation: 295
So I have a datatable and I'm using linq to get a specific row and then I want to loop over the row.
var table = myTable.AsEnumerable();
var myRow = table.Where(x => x.Field<int>("Year") == 2018);
foreach (DataRow row in myRow.Table.Rows)
{
//print row
}
However, it seems like myRow still contains all the rows. How do I get only the specific row that should results from that linq query and loop over it? I guess what i want is array of the resulting row. The resulting row contains a combination of different types including strings, ints and decimals.
I have tried
DataRow myRow2 = table.FirstOrDefault();
still the same result.
Upvotes: 0
Views: 3354
Reputation: 216342
You should loop over the result of the Where.
Where returns an enumerable of DataRow(s), so it is more appropriate the plural.
var myRows = table.Where(x => x.Field<int>("Year") == 2018);
foreach (DataRow row in myRows)
{
//print row
}
Where also doesn't filter the current table, so your code loops over the full row collection.
Another way to get a filtered set of your rows is through the Select native method. Not sure which is better in perfomances.
var myRows = table.Select("Year = 2018");
foreach (DataRow row in myRow.Table.Rows)
{
//print row
}
Upvotes: 1
Reputation: 9714
You actually just want the following for the foreach:
foreach (DataRow row in myRows)
When you have the result of your query, accessing the Table is actually pointing back to the unfiltered table, and returning all the rows associated with it.
Upvotes: 3