How do you perform a CROSS JOIN with LINQ to SQL?
如何使用LINQ to SQL执行CROSS JOIN?
交叉联接只是两组的笛卡尔乘积。 没有显式的join运算符。
1 2 3 4 5 6 7 8 9
| var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
}; |
linq扩展方法也是如此:
1 2 3 4 5 6 7 8 9
| 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);
} |
根据史蒂夫的回答,最简单的表达是这样的:
1 2 3
| var combo = from Person in people
from Car in cars
select new {Person, Car}; |
Tuple是笛卡尔积的好类型:
1 2 3 4
| 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)));
} |
扩展方式:
1 2 3 4
| 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)));
} |
并使用像:
|