如何使用LINQ to SQL执行CROSS JOIN?
答案 0 :(得分:138)
交叉连接只是两组的笛卡尔积。它没有明确的连接运算符。
var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour };
答案 1 :(得分:31)
与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);
}
答案 2 :(得分:22)
根据史蒂夫的回答,最简单的表达方式是:
var combo = from Person in people
from Car in cars
select new {Person, Car};
答案 3 :(得分:9)
对于笛卡尔积,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)));
}
答案 4 :(得分:3)
扩展方法:
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)