C# foreach with index: getting the current iteration index
Learn how to get the current index inside a C# foreach loop using a counter, LINQ Select, or a for loop, and understand the tradeoffs.

When you need the current index inside a C# foreach loop, the loop itself does not provide it. The foreach statement iterates over a collection without exposing the position of the current element. This article explains common ways to obtain that index and the tradeoffs of each approach.
Why foreach Does Not Expose an Index
The foreach statement is designed to work with any type that exposes a GetEnumerator method, and in practice most collections implement IEnumerable<T>. It calls GetEnumerator and then repeatedly calls MoveNext and reads Current. The enumerator does not provide a public index property. That is why the loop syntax does not include an index variable. If you need the position, you have to derive it from the collection structure or use a different loop construct.
Using a Counter Variable
The simplest approach is to declare a counter before the loop and increment it after each iteration. This works with any collection type and does not require changing the loop syntax.
var items = new List<string> { "apple", "banana", "cherry" };
int index = 0;
foreach (var item in items)
{
Console.WriteLine($"{index}: {item}");
index++;
}The counter is just a local variable. It starts at zero and increases by one after each iteration. This matches the natural zero-based indexing used by arrays and most collections. The main risk is forgetting to increment the counter, which would cause every iteration to see the same index. In a longer loop, that mistake can be hard to spot because the code still compiles and runs.
Using LINQ Select to Carry the Index
The LINQ Select method has an overload that passes the index to the selector function. You can combine that with a tuple to keep the item and its index together.
foreach (var (item, index) in items.Select((item, index) => (item, index)))
{
Console.WriteLine($"{index}: {item}");
}This approach avoids a separate counter variable. The index is computed by the enumerator internally and passed to the selector. The resulting sequence contains a (item, index) value tuple, and the foreach loop deconstructs it directly. This is more functional in style and can be useful when you need to transform the collection while also tracking position.
However, it does add an extra layer of indirection. Select creates a new enumerable iterator that wraps the original, and every iteration invokes the selector delegate and constructs a (item, index) value. Because this value is a ValueTuple, it normally does not allocate a separate heap object per element. The delegate itself is allocated once, not once per item. For most collections the overhead is small, but it is not free.
Using a for Loop Instead
If the collection supports direct indexing, a for loop is often the clearest way to get the index. Arrays, List<T>, and other types with an indexer can be used this way.
for (int i = 0; i < items.Count; i++)
{
var item = items[i];
Console.WriteLine($"{i}: {item}");
}The for loop gives you explicit control over the index variable, the condition, and the increment. It is easy to read and does not rely on a separate counter or a LINQ iterator. The limitation is that not every collection implements an indexer. A LinkedList<T> or a custom IEnumerable<T> that does not expose an indexer cannot be used with this pattern. In those cases you would need to fall back to a counter or LINQ.
Performance and Allocation Considerations
The counter approach adds only an integer increment per iteration, which is essentially free. The LINQ Select approach creates an iterator and passes each element through a delegate call, constructing a (item, index) value-tuple value per element. The actual cost depends on the collection size and the .NET version. In modern .NET, this is often well optimized, but it still involves a delegate invocation and value-tuple construction per item. If you are processing millions of items in a tight loop, the difference can matter. The for loop uses the indexer directly and is generally comparable to a foreach loop for indexable collections. The choice should be based on the collection type and the performance requirements of the surrounding code. Without measurements, it is safer to assume that the counter and for loop have lower overhead than the LINQ approach.
Maintainability and Readability Tradeoffs
The counter variable is easy to understand but easy to misuse. If the loop body is long, the increment line might be far from the top, making it less obvious that the index is being updated. The LINQ version is compact and keeps the index tied to the item, but it can be less familiar to developers who are not comfortable with tuple deconstruction. The for loop is explicit and widely understood, but it only works with indexable collections. Choose the approach that matches the team's style and the collection's capabilities. For a one-off script, the counter is usually fine. For a codebase where functional patterns are common, the LINQ version may fit better.
Edge Cases: Null and Empty Collections
A direct foreach loop throws a NullReferenceException when it tries to get an enumerator from a null collection. Passing null to LINQ Select throws an ArgumentNullException before iteration begins, because Select checks its source argument. A for loop throws a NullReferenceException when it evaluates items.Count. In all three cases, check for null before the loop if null is possible.
An empty collection is not a problem; the loop simply does not execute. With a counter, the index variable remains at its initial value after the loop. With LINQ, the Select sequence is empty, so the foreach body never runs. With a for loop, the condition is false from the start, so the loop is skipped. These behaviors are consistent, but you should be aware of them when writing code that relies on the index after the loop.
Choosing the Right Approach
There is no single best way to get the index in a foreach loop. The decision depends on the collection type, the surrounding code, and the performance profile you need. Use a counter when you want the simplest possible solution and the collection does not support indexing. Use LINQ Select when you prefer a functional style and the collection is small or the overhead is acceptable. Use a for loop when the collection has an indexer and you want explicit control. The key is to be consistent within a codebase so that readers can predict how the index is obtained.
| Approach | Readability | Applicability | Overhead |
|---|---|---|---|
| Counter | High | Any IEnumerable | Minimal |
| LINQ Select | Moderate | Any IEnumerable | Delegate call and ValueTuple construction per item |
| For loop | High | Indexable collections | Minimal |
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.