问题描述
如何获得列表中所有可能的项目对(顺序不相关)?
How do I get all possible pairs of items in a list (order not relevant)?
例如如果我有
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)
}
推荐答案
对 cgeers 答案进行轻微的重新表述,以获得你想要的元组而不是数组:
Slight reformulation of cgeers answer to get you the tuples you want instead of arrays:
var combinations = from item1 in list
from item2 in list
where item1 < item2
select Tuple.Create(item1, item2);
(如果需要,请使用 ToList
或 ToArray
.)
(Use ToList
or ToArray
if you want.)
以非查询表达式形式(稍微重新排序):
In non-query-expression form (reordered somewhat):
var combinations = list.SelectMany(x => list, (x, y) => Tuple.Create(x, y))
.Where(tuple => tuple.Item1 < tuple.Item2);
这两个实际上都会考虑 n2 个值而不是 n2/2 个值,尽管它们最终会得到正确的答案.另一种选择是:
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:
var combinations = list.SelectMany((x, i) => list.Skip(i + 1), (x, y) => Tuple.Create(x, y));
... 但这使用了可能也未优化的Skip
.老实说,这可能无关紧要 - 我会选择最适合您使用的那个.
... 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 获取列表中的所有对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!