TheDeveloperBlog.com


C# Loop Over Two Variables

Loops cannot iterate over individual variables. But with a conditional expression, each iteration can use a different variable. The first iteration of the loop must use variable one. The second iteration must use variable two.

Looping over two variables

Method A - int[]:    1064 ms
Method B - for:       480 ms
Method C - do while:  254 ms [fastest]


Example. First, you may have encountered this problem often. Your method may receive two separate parameters, but you want only one loop over them. It is often best to refactor the logic into separate methods.

Here: We see three code samples that accomplish this task. Each method receives two parameters, and it must loop over them in one pass.

MethodsStatic Method
Loop example 1: C#

static int A(int a, int b)
{
    int r = 0;

    int[] arr = new int[2];
    arr[0] = a;
    arr[1] = b;
    for (int i = 0; i <= 1; i++)
    {
	int m = arr[i];
	r += m;
    }
    return r;
}

Loop example 2: C#

static int B(int a, int b)
{
    int r = 0;
    for (int i = 0; i <= 1; i++)
    {
	int m = (i == 0) ? a : b;
	r += m;
    }
    return r;
}

Loop example 3: C#

static int C(int a, int b)
{
    int r = 0;
    int i = 0;
    int m = a;

    do
    {
	if (i == 1)
	{
	    m = b;
	}
	r += m;
    } while (i++ < 1);

    return r;
}

Method A creates a temporary array. It loops over each element in that array with a for-loop. It sums the total. This is just for the example and isn't the focus. The program uses the for-loop construct in the C# language.

For

Method B receives two ints. It loops over 0 and 1. There are always two iterations in this loop. It uses the ternary operator. The question mark acts like a simple if-statement. It is equivalent functionally to method A.

Note: You can find more information, and examples, on the ternary operator on this web site.

Ternary Operator

Method C is similar to method B. The difference here is that I refactored the loop to avoid checking the range on the first iteration. It is overly complex. The do-while syntax, and the post-increment syntax is not easy to read.

Do

Discussion. After showing the loops work correctly, I benchmarked them for 100 million iterations, and took the average of ten trials. Creating a temporary array was more than two times slower than using the ternary operator or the if-statement.

And: Method C, which uses the do-while loop, was the fastest. It also has the hardest-to-read code.

Refactoring. Often you can refactor your method to call two internal methods and entirely avoid the loop. However, sometimes that makes your code harder to understand due to return values.


Summary. We looked at ways to rewrite loops in the C# language. These are three ways you can loop over two values. The second and third methods were the fastest. Sometimes it is easier to avoid refactoring code into sub-methods.