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?
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:
If you need to do something different with the last element then you’d need something like:
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
Lastmay 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: