Foreach loop, determine which is the last iteration of the loop

mishap picture mishap · Sep 19, 2011 · Viewed 256.6k times · Source

I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

 foreach (Item result in Model.Results)
 {
      //if current result is the last item in Model.Results
      //then do something in the code
 }

Can I know which loop is last without using for loop and counters?

Answer

ChrisF picture ChrisF · Sep 19, 2011

If you just need to do something with the last element (as opposed to something different with the last element then using LINQ will help here:

Item last = Model.Results.Last();
// do something with last

If you need to do something different with the last element then you'd need something like:

Item last = Model.Results.Last();
foreach (Item result in Model.Results)
{
    // do something with each item
    if (result.Equals(last))
    {
        // do something different with the last item
    }
    else
    {
        // do something different with every item but the last
    }
}

Though you'd probably need to write a custom comparer to ensure that you could tell that the item was the same as the item returned by Last().

This approach should be used with caution as Last may well have to iterate through the collection. While this might not be a problem for small collections, if it gets large it could have performance implications. It will also fail if the list contains duplicate items. In this cases something like this may be more appropriate:

int totalCount = result.Count();
for (int count = 0; count < totalCount; count++)
{
    Item result = Model.Results[count];

    // do something with each item
    if ((count + 1) == totalCount)
    {
        // do something different with the last item
    }
    else
    {
        // do something different with every item but the last
    }
}