简体   繁体   English

如何在 C# 中对两个列表进行笛卡尔连接?

[英]How do I take the Cartesian join of two lists in c#?

How do I take the Cartesian join of two lists with integers in them?如何对两个包含整数的列表进行笛卡尔连接?

Can this be done with linq?这可以用linq完成吗?

Assuming you mean a "cross join" or "Cartesian join":假设您的意思是“交叉连接”或“笛卡尔连接”:

var query = from x in firstList
            from y in secondList
            select new { x, y }

Or:或者:

var query = firstList.SelectMany(x => secondList, (x, y) => new { x, y });

If you want something else (as you can see from comments, the term "cross product" has caused some confusion), please edit your question appropriately.如果您想要其他东西(正如您从评论中看到的那样,“交叉产品”一词引起了一些混乱),请适当地编辑您的问题。 An example would be very handy :)一个例子会非常方便:)

出于好奇,实现此目的的另一种方法(产生与 Jon Skeet 的答案相同的结果)是:

firstList.Join(secondList, x => true, y => true, (m, n) => new { m, n });

If you're not fond of the query syntax (like myself), MoreLINQ provides a method for it that's cleaner, in my opinion:如果你不喜欢查询语法(比如我自己), MoreLINQ为它提供了一种简洁的方法,在我看来:

using MoreLinq;

// ....

firstList.Cartesian(secondList, (x, y) => new { x, y });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM