如何使用 LINQtoSQL 执行交叉连接?

如何使用 LINQtoSQL 执行交叉连接?

62886 次浏览

交叉连接只是两个集合的笛卡儿积,没有明确的连接操作符。

var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
};

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

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

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

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

扩展方法:

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)