1. Manually maintain index variables
Implementation method:
Declare the index variable outside the loop, incrementing manually every time you loop:
int index = 0; foreach (var item in collection) { ($"{index}: {item}"); index++; }
Features:
- Simple and straightforward, no need to introduce additional dependencies.
- Pay attention to thread safety and variable scope issues.
2. LINQ Select + Tuple Destruction
Implementation method:
Binding elements and indexes into tuples through the Select method, combined with the tuple deconstruction syntax of C# 7.0+:
foreach (var (item, index) in ((value, i) => (value, i))) { ($"{index}: {item}"); }
Features:
- The code is concise and requires no external variables.
- Note that namespaces and packages (old versions need to be installed manually).
3. Extension method encapsulation
Implementation method:
Custom extension method WithIndex, enhance code reusability:
public static IEnumerable<(T item, int index)> WithIndex(this IEnumerable source) { return ((item, index) => (item, index)); } // Callforeach (var (item, index) in ()) { ($"{index}: {item}"); }
Features:
- Improve code readability and reusability.
- The extension method needs to be defined in the static class.
4. IndexOf method (caution required)
Implementation method:
Call the IndexOf method of the collection to directly obtain the element index (suitable for collections such as List that support index search):
foreach (var item in collection) { int index = (item); ($"{index}: {item}"); }
Features:
- IndexOf implementation that relies on collections, only for collections that are unique to elements and support index lookup.
- Poor performance: Each loop traverses the set to look up the index, and the time complexity is O(n^2).
- Limitations: An error index may be returned when duplicate elements exist in a collection.
Performance and Applicability
- Manual maintenance index: suitable for simple scenarios, with optimal performance.
- LINQ method: Introduce slight performance overhead (such as iterator generation), but the impact on most scenarios is negligible.
- Extension method: Suitable for high-frequency usage scenarios, balancing performance and code tidyness.
- IndexOf: The element is unique and requires dynamic index search, poor performance, and duplicate elements are unreliable.
When choosing, you need to consider comprehensively based on specific requirements (such as code simplicity, performance requirements, and framework version compatibility).
This is the end of this article about four methods of obtaining circular indexes in C# foreach. For more related C# foreach, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!