Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the next value in a collection inside a foreach loop in C#?

Tags:

c#

.net

foreach

I'm working in C# and with a sorted List<T> of structs. I'm trying to iterate through the List and for each iteration I'd like to access the next member of the list. Is there a way to do this?

Pseudocode example:

foreach (Member member in List) {     Compare(member, member.next); } 
like image 714
Addie Avatar asked Mar 08 '10 19:03

Addie


People also ask

How do you go to next in forEach?

The reason why using a return statement to continue in a JavaScript forEach loop works is because when you use a forEach loop you have to pass in a callback function. The only way to continue to the next iteration is when your callback function completes and finishes running the code within itself.

Does continue break out of foreach loop?

In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop.

Can we obtain the array index using foreach loop in C#?

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 .

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

C# Program to Get the index of the Current Iteration of a foreach Loop Using Select() Method. The method Select() is a LINQ method. LINQ is a part of C# that is used to access different databases and data sources. The Select() method selects the value and index of the iteration of a foreach loop.


1 Answers

You can't. Use a for instead

for(int i=0; i<list.Count-1; i++)    Compare(list[i], list[i+1]); 
like image 72
munissor Avatar answered Sep 20 '22 08:09

munissor