C# LINQ Index — Complete Guide
In this tutorial, you'll learn about C# LINQ Index. We cover key concepts, practical examples, and best practices.
You need the index of each element while iterating — for numbering, logging position, or matching with another sequence. You declare an int i = 0 outside the loop and increment it manually. The LINQ Index method (C# 9+) pairs each element with its index.
Wrong
int i = 0;
foreach (var item in items)
{
Console.WriteLine($"{i}: {item}");
i++;
}
Output: Works. But the mutable counter is prone to errors (forgetting to increment, wrong initial value).
Right
foreach (var (index, item) in items.Index())
{
Console.WriteLine($"{index}: {item}");
}
Output: Same result. No manual counter. Index() returns IEnumerable<(int Index, T Item)>.
Index works with any LINQ method:
var numbered = items
.Where(x => x > 0)
.Index()
.Select(t => $"{t.Index}: {t.Item}")
.ToList();
Prevention
- Use
Index()to avoid manual counter variables in loops. - Use deconstruction
var (index, item)to access the tuple. - Use
.Index()before projection:.Index().Select(t => ...). - Use
.Select((item, i) => ...)instead ofIndexwhen you prefer the lambda approach. - Use
Indexwith deferred execution — the index is computed during iteration, not stored. - Use
Zipwhen you need to match indices across two sequences.
Common Mistakes with linq index
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Index is used in Doda Browser to number search results and log entries chronologically. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro