使用linq交叉连接未知数量的字符串数组

时间:2018-03-11 19:12:42

标签: c# linq cross-join

是否可以使用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字符串数组?

3 个答案:

答案 0 :(得分:2)

尝试this solutionitem中的每个result都不会显示为{x:"A", y:"B", ... },因为预测的属性数量不会相同,因此它会像{ {1}}:

["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;
}

答案 1 :(得分:1)

请尝试以下解决方案,以获得给定的笛卡尔产品&#34; N&#34;字符串数组的数量。

  [
        {
              "student_no":"3924/08",
              "firstname":"olana
        },
        {
              "student_no":"4011/08",
              "firstname":"yallem"
        }
  ]

答案 2 :(得分:0)

        [Fact]
    public void Test1()
    {
        var listOfStringList = new List<List<string>>();
        var list1 = new List<string> { "A", "B", "C" };
        var list2 = new List<string> { "AA", "BB", "CC" };
        var list3 = new List<string> { "AAA", "BBB", "CCC" };
        listOfStringList.Add(list1);
        listOfStringList.Add(list2);
        listOfStringList.Add(list3);
        var resultData = new List<List<string>>();
        listOfStringList.ForEach((stringList) =>
        {
            if (resultData.Count == 0)
            {
                resultData = stringList.Select(u => new List<string> { u }).ToList();
                return;
            }
            resultData = resultData.SelectMany(u => stringList
                .Select(v =>
                {
                    var list = new List<string>();
                    u.ForEach(sv =>
                    {
                        list.Add(sv);
                    });
                    list.Add(v);
                    return list;
                }).ToList()).ToList();
        });
        // Ignore variable resultantData it is just for highlight
        var resultantData = resultData;
    }