SoFunction
Updated on 2025-04-23

How to get indexes in C# foreach loop

1. Manually maintain index variables

Implementation method
Declare the index variable outside the loop, incrementing manually for each iteration:

int index = 0; foreach (var item in collection) { ($"{index}: {item}"); index++; } 

Features

  • Simple and straightforward, no need to introduce additional dependencies 12.
  • Pay attention to thread safety and variable scope issues.

2. LINQ Select + Tuple Destruction

Implementation method
Using LINQSelectMethods bind elements to indexes into tuples (C# 7.0+ supports tuple deconstruction syntax):

foreach (var (item, index) in ((value, i) => (value, i))) { ($"{index}: {item}"); } 

Features

  • The code is concise and avoids manual maintenance of index 13.
  • Need to be introducedNamespace.

3. Extension method encapsulate index

Implementation method
Custom extension methodWithIndex, package the collection element and index back:

public static class EnumerableExtensions { public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source) { return ((item, index) => (item, index)); } } // Call foreach (var (item, index) in ()) { ($"{index}: {item}"); } 

Features

Enhanced code reusability, suitable for scenarios where indexes are frequently obtained 3.

4. Use for loop substitution

Implementation method
If you need to operate the index directly, you can use it instead.forLoop:

for (int i = 0; i < ; i++) { var item = collection[i]; ($"{i}: {item}"); } 

Features

  • Direct access to indexes, suitable for collections that support indexers (such as arrays,List<T>)57。
  • Cannot be used for collections that do not support indexers (e.g.IEnumerable<T>)。

Method comparison and applicable scenarios

method Applicable scenarios advantage limit
Manually maintain index variables Simple scenarios, no complex dependencies required No extra dependencies, flexible Need to be managed manually, and errors are prone to
LINQ + Tuple Destruction Projects that require concise syntax and support C# 7.0+ Compact code Rely on LINQ, slightly lower performance
Extended Method High reusability requirements Reusable, clear code structure Predefined extension classes
forCircular substitution Sets that support indexers (arrays,List<T>wait) Direct and efficient Not applicable toIEnumerable<T>

Operation suggestions

  • PriorityLINQ + Tuple DestructionorExtended Method, to keep code simplicity and maintainability 13.
  • Scenarios that are sensitive to performance, use them insteadforRun or manually maintain index 57.

This is the article about how to obtain indexes in C# foreach loops. For more information about C# foreach, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!