Jeremy Stein - Brain

« »

C# foreach two at a time

Do you want to iterate through a collection with a foreach, but retrieve two items at a time?

You can’t do it. The spec states specifically that the enumerator is inaccessible.

I supposed you could do something like this:

int[] a = {1, 2, 3, 4, 5, 6};

int previousVal = -1;
bool odd = false;
foreach (int currentVal in a)
  odd = ! odd;
  if (odd)
    previousVal = currentVal;
  Console.WriteLine(String.Format("{0}, {1}",
    previousVal, currentVal));

March 29, 2006 1 Comment.

One Comment

  1. Miguel replied:

    You can do this sort of thing by working directly with the enumerator.
    Not sure if this will work with older versions of C#, you would have to put in the actual object type instead of “var” for one.

    var enumerator = a.GetEnumerator();
    while (enumerator.MoveNext()){
        var current = enumerator.Current;
        if (enumerator.MoveNext()){
            var afterCurrent = enumerator.Current;
            //here you can access "current" & "afterCurrent"
            //here you can only access "current", there is no item after this.

    October 6th, 2011 at 5:25 am. Permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Why ask?

« »