如何使用LINQ to SQL执行CROSS JOIN?


Answers:


151

交叉联接只是两组的笛卡尔乘积。没有明确的联接运算符。

var combo =来自人中的p
            从汽车中的c
            选择新的
            {
                p。名称,
                c。制作
                c。型号
                颜色
            };

2
您如何from p in people from c in cars用lambda表示法写出来?
运动

47
people.SelectMany(p => cars, (p, c) => new { ... })
伊恩·加洛韦

38

用同样的事情linq扩展方法:

var names = new string[] { "Ana", "Raz", "John" };
var numbers = new int[] { 1, 2, 3 };
var newList=names.SelectMany(
    x => numbers,
    (y, z) => { return y + z + " test "; });
foreach (var item in newList)
{
    Console.WriteLine(item);
}

25

根据史蒂夫的回答,最简单的表达是:

var combo = from Person in people
            from Car    in cars
            select new {Person, Car};

11

A Tuple是笛卡尔积的好类型:

public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)
{
    return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));
}

6

扩展方式:

public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(this IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)
{
    return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));
}

并使用像:

vals1.CrossJoin(vals2)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.