I would not go this way.
As jbueno said this is a case where for
might be a better idea, so just compare the index with the Count()
or Length
of the (possibly curly) list.
You can use the same technique within foreach
, but you would have to have the index variable to compare with the total of items (minus 1 to indicate the last number). If it is to have this variable, why not make a for
? Something like this:
var count = list.Length;
foreach(var element in list) {
if (--count > 0) {
//is last
}
}
In some cases you can use some option with foreach
. It could store the value of the last item and compare it with the current one. But you have to ensure the uniqueness of the values in the whole list. Risky.
The foreach
is suitable when you want to iterate over the list more evenly, in cases like this it is not so suitable. But it depends on each case.
If you can use another form (it does not make sense), I found a solution by unlinking what foreach
does :
using (var enumerator = .GetEnumerator()) {
var last = !enumerator.MoveNext();
T current;
while (!last) {
current = enumerator.Current;
last = !enumerator.MoveNext();
if (last) {
//is last
}
}
}
I do not really like this solution, and it can not be used in all cases, but you can use LINQ :
elements.ForEach((element, info) => {
if (info.IsLast) {
//is last
}
});
You can have other creative solutions, variations of these, but in the end changes little, you have to do what is most appropriate for the case. You can not attach to a shape, use whatever is best in the concrete case.