Possible Duplicate:
Foreach loop, determine which is the last iteration of the loop
foreach (DataRowView row in orderedTable.DefaultView)
{
if(lasttime) do-something;
}
orderedtable is a datatable
does anyone know how to find out whether we are on the last foreach iteration? please keep in mind that i do have duplicates in orderedtable
The correct method that works in all cases is to use the IEnumerator<T>
directly:
using (var enumerator = orderedTable.DefaultView.GetEnumerator())
{
if (enumerator.MoveNext())
{
bool isLast;
do
{
var current = enumerator.Current;
isLast = !enumerator.MoveNext();
//Do stuff here
} while (!isLast);
}
}
This method works even if your collection doesn't have a Count
property, and even if it does, this method will be more efficient if the Count
property is slow.
The foreach
construct does not know such a thing, since it applies equally to unbounded lists. It just has no way of knowing what is a last item.
You can iterate the manual way as well, though:
for (int i = 0; i < orderedTable.DefaultView.Count; i++) {
DataRowView row = orderedTable.DefaultView[i];
if (i == orderedTable.DefaulView.Count - 1) {
// dosomething
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With