Home >Backend Development >C++ >How Can I Get the Index of the Current Iteration in a C# Foreach Loop?
Obtaining the current iteration in the Foreach loop is a common programming task. Although C# does not provide a built -in solution, it has a unique structure that can meet this demand.
Solution: Use Select and anonymous objects
One method is to use Linq's selection method, which provides a heavy load that allows you to specify a function, which uses the value and index as a parameter. By selecting the index in this function, you can create an anonymous object containing value and index:
Optimized: Use ValueTuple and automatic deconstruction
<code class="language-csharp">foreach (var item in Model.Select((value, i) => new { i, value })) { var value = item.value; var index = item.i; }</code>
If you use C# 7.0 or higher version, you can use valueTuple instead of anonymous objects to avoid heap allocation:
In addition, automatic deconstruction does not require explicit access attributes:
<code class="language-csharp">foreach (var item in Model.Select((value, i) => (value, i))) { var value = item.value; var index = item.i; }</code>By combining these structures, you can easily retrieve the current iterative indexes in the C# FOREACH cycle, thereby improving the accuracy and flexibility of the code.
The above is the detailed content of How Can I Get the Index of the Current Iteration in a C# Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!