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
Using Last() on certain types will loop thru the entire collection!
Meaning that if you make a foreach and call Last(), you looped twice! which I'm sure you'd like to avoid in big collections.
Then the solution is to use a do while loop:
using var enumerator = collection.GetEnumerator();
var last = !enumerator.MoveNext();
T current;
while (!last)
{
current = enumerator.Current;
//process item
last = !enumerator.MoveNext();
if(last)
{
//additional processing for last item
}
}
So unless the collection type is of type IList the Last() function will iterate thru all collection elements.
Test
If your collection provides random access (e.g. implements IList), you can also check your item as follows.
if(collection is IList list)
return collection[^1]; //replace with collection.Count -1 in pre-C#8 apps