c# how to get last time in foreach statement?

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 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
    }
}

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.


An alternative approach which I don't think anyone posted. This works well if you don't know the count ahead of time.

DataRowView lastRow;
foreach (DataRowView row in orderedTable.DefaultView)
{
    // Do something...

    lastRow = row;
}

if (lastRow != null)
{
  // Do something with last row
}
链接地址: http://www.djcxy.com/p/52982.html

上一篇: 每个'循环'的Java如何工作?

下一篇: C#如何获得上次在foreach语句?