Is it possible to do a cross join using linq where the number of joins is not known in advance?
I have this:
var arrays = new List<string[]>();
If I know I have three lists I can do:
var oQuery = from x in arrays[0]
    from y in arrays[1]
    from z in arrays[2]
    select new {x, y, z};
Is it be possible to join n string arrays using linq?
Try this solution, where each item from result will not be look like {x:"A", y:"B", ... }, because number of properties is not predicted, so instead, it will be like ["A", "B", ... ]:
public static List<List<string>> CrossJoin(List<string[]> arrays)
{
    var data = arrays.Select(x => x.ToList()).ToList();
    List<List<string>> result = data[0].Select(x => new List<string> { x }).ToList();
    for (var i = 1; i < data.Count; i++)
        result = (from a in result
                  from b in data[i]
                  select new { a, b })
                  .Select(x => x.a.Concat(new List<string> { x.b }).ToList())
                  .ToList();
    return result;
}
Usage:
var arr1 = new[] { "A", "B", "C" };
var arr2 = new[] { "D", "E" };
var arr3 = new[] { "F", "G" };
var result = CrossJoin(new List<string[]> { arr1, arr2, arr3 });
for(var i = 0; i < result.Count; i++) 
    Console.WriteLine(string.Format("{0}: {1}", i + 1, string.Join(",", result[i])));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With