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

前端 未结 26 915
迷失自我
迷失自我 2020-11-28 02:56

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 Mod         


        
26条回答
  •  再見小時候
    2020-11-28 03:20

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

提交回复
热议问题