是否可以使用linq进行交叉联接,而事先不知道联接数?

我有这个:

var arrays = new List<string[]>();

如果我知道我有三个列表,则可以执行以下操作:
var oQuery = from x in arrays[0]
    from y in arrays[1]
    from z in arrays[2]
    select new {x, y, z};

是否可以使用linq连接n字符串数组?

最佳答案

尝试this solution,其中item中的每个result看起来都不像{x:"A", y:"B", ... },因为无法预测属性的数量,所以它将类似于["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;
}

用法:
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])));

关于c# - 使用linq交叉连接未知数目的字符串数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49223992/

10-12 00:09