133

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

4

5 回答 5

168

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

var combo = from p in people
            来自汽车中的c
            选择新的
            {
                p.姓名,
                c.制作,
                c.型号,
                c.颜色
            };
于 2008-09-11T14:00:40.963 回答
42

与 Linq 扩展方法SelectMany(lambda 语法)相同:

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);
}
于 2012-07-09T13:13:15.657 回答
26

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

var combo = from Person in people
            from Car    in cars
            select new {Person, Car};
于 2009-03-24T20:43:21.047 回答
13

ATuple是笛卡尔积的好类型:

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)));
}
于 2013-09-21T21:37:16.980 回答
7

扩展方法:

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)
于 2016-03-18T16:45:15.083 回答