C# Reference ยท LINQ
LINQ Index() method
Reference for LINQ Index() in C# (.NET 9): enumerate a sequence as (Index, Item) tuples instead of using Select with an index or a manual counter.
Index() pairs every element with its zero-based position. It returns a sequence of (int Index, TSource Item) tuples, so you can write foreach (var (i, item) in list.Index()) without keeping a counter by hand or using Select((x, i) => ...).
It was added in .NET 9. It is lazy and streams: positions are counted as the source is enumerated, and the source is read only once.
foreach (var (i, name) in names.Index()) { Console.WriteLine($"{i}: {name}"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static IEnumerable<(int Index, TSource Item)> Index<TSource>( this IEnumerable<TSource> source);
| Name | Description |
|---|---|
source |
The sequence to number. |
Returns: a lazily evaluated sequence of tuples with the position (starting at 0) and the original element.
Errors: ArgumentNullException if source is null.
Usage notes
- Requires .NET 9 or later.
- Not the
Indextype.System.Index(the^1operator) is unrelated; this method is just a counter attached to each item. See index and range operators. - Same as
Select.source.Index()is equivalent tosource.Select((item, index) => (index, item)), with the tuple order(Index, Item). - Deferred execution. Nothing is read until enumeration; each enumeration restarts the numbering at
0. - Prefer a
forloop when you have an array orList<T>and need to change elements or skip around;Index()shines when the source is a lazy sequence. - Cost. O(1) extra memory and no copying: each element is wrapped in a tuple as it passes through.
Related
Select(),Where(),Zip(),Take(),Skip(),Chunk()- Lessons: LINQ basics, LINQ operators