Skip to content
Tutorials Center
My learning

Topics

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.

C#
foreach (var (i, name) in names.Index())
{
    Console.WriteLine($"{i}: {name}");
}

Try it

C# Numbering elements

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.

C# Finding positions

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

C#
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 Index type. System.Index (the ^1 operator) is unrelated; this method is just a counter attached to each item. See index and range operators.
  • Same as Select. source.Index() is equivalent to source.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 for loop when you have an array or List<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.