Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to get last time in foreach statement? [duplicate]

Tags:

c#

.net

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

like image 534
JOE SKEET Avatar asked Jan 17 '11 19:01

JOE SKEET


2 Answers

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.

like image 109
user541686 Avatar answered Oct 23 '22 00:10

user541686


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
    }
}
like image 44
Joey Avatar answered Oct 23 '22 01:10

Joey