Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?
For instance, I currently do something like this depending on the circumstances:
int i = 0; foreach (Object o in collection) { // ... i++; }
C#'s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .
Infer the foreach loop variable type automatically with var The foreach loop is an elegant way to loop through a collection. With this loop we first define a loop variable. C# then automatically sets that variable to each element of the collection we loop over. That saves some of the hassles that other loops have.
How foreach loop works? The in keyword used along with foreach loop is used to iterate over the iterable-item . The in keyword selects an item from the iterable-item on each iteration and store it in the variable element . On first iteration, the first item of iterable-item is stored in element.
The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?
Ian Mercer posted a similar solution as this on Phil Haack's blog:
foreach (var item in Model.Select((value, i) => new { i, value })) { var value = item.value; var index = item.i; }
This gets you the item (item.value
) and its index (item.i
) by using this overload of LINQ's Select
:
the second parameter of the function [inside Select] represents the index of the source element.
The new { i, value }
is creating a new anonymous object.
Heap allocations can be avoided by using ValueTuple
if you're using C# 7.0 or later:
foreach (var item in Model.Select((value, i) => ( value, i ))) { var value = item.value; var index = item.i; }
You can also eliminate the item.
by using automatic destructuring:
foreach (var (value, i) in Model.Select((value, i) => ( value, i ))) { // Access `value` and `i` directly here. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With