You are walking a sequence and need both the item and its position. The usual answer is a counter you increment by hand. It works, but now you have one more thing to keep in sync.
In .NET 9 and later, Enumerable.Index() gives you both values together.
Try It
Create a .NET 10 console app:
dotnet new console -n EnumerableIndexDemo -f net10.0cd EnumerableIndexDemoReplace Program.cs with this:
var names = new[] { "Ada", "Grace", "Katherine" };
foreach (var (index, name) in names.Index()){ Console.WriteLine($"{index}: {name}");}Run it:
dotnet runThe index starts at zero, just like an array index.
The Part That Matters
Index() returns each item with its zero based index. It does not turn the source into a list or give you random access. It just keeps the current position alongside each item as you enumerate.
That makes it handy for adding line numbers, reporting progress, or pairing a sequence with its position. If the index is part of the actual data, put it in the data instead.
Key Takeaway
Use Enumerable.Index() when you need an item’s position during a foreach. One less counter to babysit.