Jeremy Stein - Brain
« Visual Studio .NET Task List – View All | .NET Generic Method to Run a Stored Procedure » |
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;
continue;
}
Console.WriteLine(String.Format("{0}, {1}",
previousVal, currentVal));
}
One Comment
- 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" }else{ //here you can only access "current", there is no item after this. } }
October 6th, 2011 at 5:25 am. Permalink.
« Visual Studio .NET Task List – View All | .NET Generic Method to Run a Stored Procedure » |
Leave a Reply