I wouldn’t go this way.
As LINQ said this is a case where the for
might be a better idea, so just compare the index with the Count()
or Length
from the list (possibly curly).
It is possible to use the same technique within a foreach
, but it would have to have the index variable to compare with the total of items (minus 1 to indicate the number of the latter). If it is to have this variable, why not make a for
? Something like that:
var count = list.Length;
foreach(var element in list) {
if (--count > 0) {
//is last
}
}
In some cases it is possible to use some option with foreach
. You could store the value of the last item and compare it to the current one. But you have to ensure the uniqueness of the values in the whole list. Risky.
The foreach
is suitable when one wants to iterate on the list more evenly, in cases so it is not so suitable. But it depends on each case.
If you can use another form (it doesn’t make so much sense), I found a solution unlocking what the foreach
ago:
using (var enumerator = .GetEnumerator()) {
var last = !enumerator.MoveNext();
T current;
while (!last) {
current = enumerator.Current;
last = !enumerator.MoveNext();
if (last) {
//is last
}
}
}
I don’t really like this solution, and it can’t be used in all cases, but you can use LINQ:
elements.ForEach((element, info) => {
if (info.IsLast) {
//is last
}
});
I put in the Github for future reference.
You can have other creative solutions, variations of these, but in the end it changes little, you have to do what is most suitable for the case. You can’t hold on to a shape, use what’s best in the particular case.
There are cases that the
Last()
will end up iterating through the entire collection. Is it a good idea to use afor
?– Jéf Bueno