选择一个列表的所有独特的组合,没有重复,使用LINQ [英] Select all unique combinations of a single list, with no repeats, using LINQ
问题描述
我有号码的列表,我需要创建列表中的号码的每一种可能的独特的组合,而不重复使用LINQ查询。因此,举例来说,如果我有 {1,2,3}
,组合将是 1-2
, 1-3
和 2-3
。
I have a list of numbers, and I need to create every possible unique combination of the numbers in the list, without repeats, using a LINQ query. So, for example, if I have { 1, 2, 3 }
, the combinations would be 1-2
, 1-3
, and 2-3
.
我目前使用两个为
循环,就像这样:
I currently use two for
loops, like so:
for (int i = 0; i < slotIds.Count; i++)
{
for (int j = i + 1; j < slotIds.Count; j++)
{
ExpressionInfo info1 = _expressions[i];
ExpressionInfo info2 = _expressions[j];
// etc...
}
}
是否有可能转换这两个为
循环到LINQ?
Is it possible to convert these two for
loops to LINQ?
感谢。
推荐答案
当然 - 你可以使用嵌入的呼叫做中的SelectMany
单呼跳过
:
Sure - you can do it in a single call to SelectMany
with an embedded call to Skip
:
var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
(first, second) => new { first, second });
下面是一个替代方案,不使用的非常的这样一个深奥的超载的SelectMany
:
Here's an alternative option, which doesn't use quite such an esoteric overload of SelectMany
:
var query = from pair in slotIds.Select((value, index) => new { value, index })
from second in slotIds.Skip(pair.index + 1)
select new { first = pair.value, second };
这基本上做同样的事情,只是方式略有不同。
These do basically the same thing, just in slightly different ways.
下面是另一个选项,它是更接近原始的:
Here's another option which is much closer to your original:
var query = from index in Enumerable.Range(0, slotIds.Count)
let first = slotIds[index] // Or use ElementAt
from second in slotIds.Skip(index + 1)
select new { first, second };
这篇关于选择一个列表的所有独特的组合,没有重复,使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!