How to perform cartesian product of two arrays using Linq in C#

2 Answers

0 votes
using System;
using System.Linq;
  
class Program
{
    static void Main() {
        char[] letters = "abcdefg".ToCharArray();
        char[] digits  = "1234567".ToCharArray();
        
        var result = from l in letters
                     from d in digits
                     select $"{l}{d}";
        
        foreach (var pair in result) {
            Console.Write($"{pair} ");
        
            if (pair.EndsWith("7")) {
                Console.WriteLine();
            }
        }
    }
}
  
 
  
/*
run:
  
a1 a2 a3 a4 a5 a6 a7 
b1 b2 b3 b4 b5 b6 b7 
c1 c2 c3 c4 c5 c6 c7 
d1 d2 d3 d4 d5 d6 d7 
e1 e2 e3 e4 e5 e6 e7 
f1 f2 f3 f4 f5 f6 f7 
g1 g2 g3 g4 g5 g6 g7 
  
*/

 



answered Jul 4, 2023 by avibootz
edited Jul 4, 2023 by avibootz
0 votes
using System;
using System.Linq;
  
class Program
{
    static void Main() {
        char[] letters = "abcd".ToCharArray();
        char[] digits  = "1234".ToCharArray();
        
        var result = letters.SelectMany(x => digits, (x, y) => new { x, y });

        foreach (var pair in result) {
            Console.WriteLine("{0}{1}", pair.x, pair.y);
        }
    }
}
  
 
  
/*
run:
  
a1
a2
a3
a4
b1
b2
b3
b4
c1
c2
c3
c4
d1
d2
d3
d4

*/

 



answered Jul 4, 2023 by avibootz
edited Jul 4, 2023 by avibootz

Related questions

3 answers 159 views
1 answer 118 views
1 answer 115 views
1 answer 149 views
...