1

in Product SKUs, we can get Cartesian Product in the way of LINQ:

string[] arr1 = new[] {"red", "blue", "orange"};
string[] arr2 = new[] {"5 inche", "8 inch"};
var result = from a in arr1
             from b in arr2
             select a + " " + b;
foreach (var item in result){
    Console.WriteLine(item);
}

We know the exact number of arrays.

My question is: If the number of arrays is dynamic, how do we get Cartesian Product?

Thanks.

Raein Hashemi
  • 3,346
  • 4
  • 22
  • 33
darrenji
  • 75
  • 1
  • 5

2 Answers2

3

I liked Raeen's answer and it made me think of a simple linq way to solve this problem. This is a very similar method, but doesn't involve any state external to the computation.

var list = new List<IEnumerable<string>>()
{
    new[] {"red", "blue", "orange"},
    new[] {"5 inche", "8 inch"},
    new[] {"x", "y"},
};

var result =
    list
        .Aggregate((rs, vs) =>
            from r in rs
            from v in vs
            select r + " " + v)
        .ToList();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • +1. I think this is *a lot* prettier than the accepted answer due to no mutable state outside of `Aggregate`. May I suggest adding `list.DefaultIfEmpty(Enumerable.Empty())` before the call to `Aggregate` so as to avoid the `InvalidOperationException` if `list.Count` is zero? – Kirill Shlenskiy Nov 18 '14 at 00:55
0

I'd put them in a list of string arrays. Then I'd use ForEach:

IEnumerable<string> result = list.First();

list.RemoveAt(0);

list.ForEach(delegate(IEnumerable<string> value)
{
     result = (from r in result
               from v in value
               select r + " " + v).ToList();

});

You can also see this link : Cartesian Product for Group members

Community
  • 1
  • 1
Raein Hashemi
  • 3,346
  • 4
  • 22
  • 33
  • @Enigmativity If we have many arrays and we don't know the count of them, the only way I can think of is a ForEach on the list and every time, we use that Linq on every array and the previous results we got from the previous arrays. See the link for another example. – Raein Hashemi Nov 17 '14 at 13:34
  • 1
    Very clever. I generally try to avoid state and use recursion instead for these kinds of things. Interesting approach. – Enigmativity Nov 17 '14 at 22:52