Actually if you really need the index, the right thing is to use the for
.
If you don’t want to use the right tool for the problem, the most obvious solution is the one presented in the question.
Otherwise the solution that people usually make is to use LINQ, what I find an exaggeration for the problem and very rarely is a better solution than the previous ones in any analysis that is made - if you do a general analysis, I doubt that it is good in any situation. It would be something like that:
foreach (var pair in list.Select((x, i) => new {Index = i, Value = x})) {
WriteLine($"{pair.Index}: {pair.Value}");
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I find it less readable, less performative and I can’t see any gain.
Some prefer to create some abstraction on top of that, such as an extension method that hides a little the implementation details, or a class that handles it. In rare cases I find it appropriate. Depending on the case (where a method replaces the loop) it changes the semantics and few programmers know how to handle it right. Ends up being an exaggeration to avoid the obvious and simple use.
What could make it a little better, something like that:
foreach (var pair in list.IndexPair()) {
WriteLine($"{pair.Index}: {pair.Value}");
}
public static class IEnumerableExt {
public static IEnumerable<T> IndexPair(this IEnumerable<T> enumerable) {
return enumerable.Select((x, i) => new {Index = i, Value = x});
}
}
I’ve seen some solutions so bizarre that I refuse to post here.
using is not an option?
– Nicolas Bontempo
@Nicolasbontempo my doubt is limited to the
foreach
even.– vinibrsl
Related: How to determine the last element of a list in a foreach?
– Jéf Bueno