Actually if you really need the index, the right thing is to use for
.
If you do not want to use the right tool for the problem, the most obvious solution is the one presented in the question.
Otherwise the solution is to use LINQ, which I think is an exaggeration for the problem and is rarely a better solution than the previous ones in any analysis that is done - if I make a general analysis, I doubt that she is good in any situation. It would look something like this:
foreach (var pair in list.Select((x, i) => new {Index = i, Value = x})) {
WriteLine($"{pair.Index}: {pair.Value}");
}
See working on dotNetFiddle .
I find it less legible, less performative and I can not see any gain.
Some prefer to create some abstraction on top of this, such as an extension method that hides the implementation details a bit, or a class that deals with it. In rare cases I find it appropriate. Depending on the case (where a method overrides the loop) changes the semantics and few programmers know how to handle it right. It ends up being overkill to avoid obvious and simple use.
What could make it a bit better, something like this:
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 strange that I refuse to post here.