如何执行与LINQ to SQL的CROSS JOIN?

如何执行与LINQ to SQL的CROSS JOIN?

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

 var combo =从p在人
            从C在汽车
            select新的
             {
                 p.Name,
                 c.Make,
                 c.Model,
                 c.Colour
             };

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); } 

根据史蒂夫的回答,最简单的expression就是:

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

Tuple是笛卡尔积的一个很好的types:

 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))); } 

扩展方法:

 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)