Iterate over multiple collections with single foreach

Avernite

Member
Joined
Jan 17, 2023
Messages
18
Programming Experience
10+
A convenience thing; it would be nice to write:

C#:
// Assume factors = int[] {1..12}

foreach (int m in factors, int n in factors) // iterate over multiple collections
  Debug.Log(string.Format("{0} x {1} = {2}", m, n, m * n));

Instead of:

C#:
foreach (int m in factors)
  foreach (int n in factors)
    Debug.Log(string.Format("{0} x {1} = {2}", m, n, m * n));

Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
:
:
12 x 11 = 132
12 x 12 = 144

(144 lines)
 
An example with Linq:
C#:
var factors = Enumerable.Range(1, 12).ToArray();
var combinations = from m in factors from n in factors select (m, n);
foreach (var (m, n) in combinations)
    Console.WriteLine(string.Format("{0} x {1} = {2}", m, n, m * n));
 
It's better to make an extension method and give the method a good name. Something like CrossJoin(), perhaps. Yes, it'll be more keystrokes to create the extension method, but in the end, a well named method will provide extra documentation about what is happening without having to write comments.
 

Latest posts

Back
Top Bottom