Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the index of the current iteration of a foreach loop?

Tags:

c#

foreach

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++; } 
like image 973
Matt Mitchell Avatar asked Sep 04 '08 01:09

Matt Mitchell


People also ask

Can I get index in foreach loop?

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 .

What is VAR in foreach loop?

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.

What is the syntax of the foreach loop?

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.

When to use foreach loop explain it with an example?

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: <?


1 Answers

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. } 
like image 72
bcahill Avatar answered Sep 19 '22 15:09

bcahill