Retrieving the Iteration Index within a C# foreach
Loop
C#'s foreach
loop doesn't inherently provide access to the iteration index. However, we can cleverly use LINQ's Select
method to achieve this.
Ian Mercer's approach, using Select
's overload that accepts a lambda expression with value and index parameters, is highly effective:
<code class="language-csharp">foreach (var item in Model.Select((value, i) => new { i, value })) { var value = item.value; var index = item.i; }</code>
The lambda expression (value, i) => new { i, value }
creates an anonymous object containing both the item (value
) and its index (i
).
For better performance and to avoid unnecessary heap allocations (especially beneficial with large collections), consider using ValueTuple
(available from C# 7.0 onwards):
<code class="language-csharp">foreach (var item in Model.Select((value, i) => (value, i))) { var value = item.value; var index = item.i; }</code>
Even more concisely, and leveraging C#'s destructuring capabilities, we can directly access the value and index:
<code class="language-csharp">foreach (var (value, i) in Model.Select((value, i) => (value, i))) { // Access `value` and `i` directly here. }</code>
These methods effectively allow you to obtain the current iteration index while using a foreach
loop, providing greater control and flexibility in your code.
The above is the detailed content of How Can I Access the Current Iteration Index in a C# foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!