使用 LINQ 获取列表中的所有对
如何获取列表中所有可能的项目对(顺序不相关)?
例如,如果我有,
var list = { 1, 2, 3, 4 };
我想得到这些元组:
var pairs = {
new Tuple(1, 2), new Tuple(1, 3), new Tuple(1, 4),
new Tuple(2, 3), new Tuple(2, 4)
new Tuple(3, 4)
}
How do I get all possible pairs of items in a list (order not relevant)?
E.g. if I have
var list = { 1, 2, 3, 4 };
I would like to get these tuples:
var pairs = {
new Tuple(1, 2), new Tuple(1, 3), new Tuple(1, 4),
new Tuple(2, 3), new Tuple(2, 4)
new Tuple(3, 4)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对 cgeers 答案进行稍微重新表述,以获得所需的元组而不是数组:(
如果需要,请使用
ToList
或ToArray
。)以非查询表达式形式(稍微重新排序 ) ):
这两个实际上都会考虑 n2 值而不是 n2/2 值,尽管它们最终会得到正确的答案。另一种选择是:
...但这使用
Skip
,它可能也未得到优化。老实说,这可能并不重要 - 我会选择最适合您使用的一个。Slight reformulation of cgeers answer to get you the tuples you want instead of arrays:
(Use
ToList
orToArray
if you want.)In non-query-expression form (reordered somewhat):
Both of these will actually consider n2 values instead of n2/2 values, although they'll end up with the correct answer. An alternative would be:
... but this uses
Skip
which may also not be optimized. It probably doesn't matter, to be honest - I'd pick whichever one is most appropriate for your usage.计算笛卡尔积以确定所有可能的组合。
例如:
您可以在此处找到有关使用 LINQ 计算笛卡尔积的更多信息:
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
然后您可以将其转换元组对象的集合。
或者简而言之:
Calculate the Cartesian product to determine all the possible combinations.
For example:
You can find more information about calculating a cartesian product using LINQ here:
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
You can then convert it to a collection of Tuple objects.
Or in short:
你可以这样解决:
You could solve it like this: