Reputation: 20468
Please take a look at this link.
Now i have a foreach like this :
//DataRow last = dsRequests.Tables["Requests"].Rows.Last();
foreach (DataRow drRequests in dsRequests.Tables["Requests"].Rows)
{
}
I want to determine the last iteration of the foreach loop.
So i tried this :
DataRow last = dsRequests.Tables["Requests"].Rows.Last();
But I have this error:
Error CS1061 'DataRowCollection' does not contain a definition for 'Last' and no extension method 'Last' accepting a first argument of type 'DataRowCollection' could be found (are you missing a using directive or an assembly reference?)
How can I do that?
Upvotes: 0
Views: 1235
Reputation: 216243
You can simply write
DataRow last = dsRequests.Tables["Requests"].AsEnumerable().LastOrDefault();
if(last != null)
.....
forcing the DataTable to be enumerable then you can use LastOrDefault(). Notice that I am using LastOrDefault because, if the table is empty, Last() will get you an exception.
Another approach is through the old fashioned index over the Rows collection
DataRow last = null;
int idx = dsRequests.Tables["Requests"].Rows.Count;
if(idx > 0) last = dsRequests.Tables["Requests"].Rows[idx -1];
if(last != null)
....
In this example you have to test the number of rows after getting the count.
I should also add that the last example using the index to access the last row is more performant. However my tests show that on a 100000 loop the difference is simply 40 millisecs. Nothing to worry about.
Upvotes: 2