0

Let's say i have two arrays.

One is

1, 2, 3

The other one is

-1, -2, -3

What Linq function(s) should i use to get all the combinations, using the index? This should be the result:

1, 2, 3
-1, 2, 3
1, -2, 3
1, 2, -3
-1, -2, 3
-1, 2, -3
1, -2, -3
-1, -2, -3

1 Answers1

0

Please note, that you have 2**n (where n = Min(x, y)) records:

  0000...0000 - all items from x
  0000...0001 - all items from x except the last item which is from y
  ...
  1111...1110 - all items from y except the last item which is from x
  1111...1111 - all items from y 

Code:

  int[] x = new int[] { 1, 2, 3 };
  int[] y = new int[] { -1, -2, -3 };

  int n = Math.Min(x.Length, y.Length);

  var result = Enumerable
    .Range(0, 1 << n)
    .Select(i => Convert
       .ToString(i, 2)
       .PadLeft(n, '0')
       .Select((c, index) => c == '0' ? x[index] : y[index])
       .ToArray())
    .ToArray();

  // Let's have a look:
  string report = string.Join(Environment.NewLine, result
    .Select(line => string.Join(", ", line)));

  Consoe.Write(report);

Outcome:

1, 2, 3
1, 2, -3
1, -2, 3
1, -2, -3
-1, 2, 3
-1, 2, -3
-1, -2, 3
-1, -2, -3
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215