C# 如何使用 LINQ to SQL 执行 CROSS JOIN?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/56547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you perform a CROSS JOIN with LINQ to SQL?
提问by Luke Smith
How do you perform a CROSS JOIN with LINQ to SQL?
如何使用 LINQ to SQL 执行 CROSS JOIN?
采纳答案by Steve Morgan
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
交叉连接只是两个集合的笛卡尔积。没有明确的连接运算符。
var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour };
回答by Mark Cidade
Based on Steve's answer, the simplest expression would be this:
根据史蒂夫的回答,最简单的表达是这样的:
var combo = from Person in people
from Car in cars
select new {Person, Car};
回答by Rzv.im
The same thing with linq
extension methods:
用同样的事情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);
}
回答by amoss
A Tuple
is a good type for Cartesian product:
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)));
}
回答by Denis
Extension Method:
扩展方法:
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)));
}
And use like:
并使用如下:
vals1.CrossJoin(vals2)