我有一个数字列表,我需要使用LINQ查询创建列表中数字的每个可能的唯一组合,不重复.因此,举例来说,如果我有{ 1, 2, 3 }
,组合将是1-2
,1-3
和2-3
.
我目前使用两个for
循环,如下所示:
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...
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以将这两个for
循环转换为LINQ?
谢谢.
Jon*_*eet 30
当然 - 你可以SelectMany
通过嵌入式调用一次性调用Skip
:
var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
(first, second) => new { first, second });
Run Code Online (Sandbox Code Playgroud)
这里的另一种选择,不使用相当的这样一个深奥的过载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 };
Run Code Online (Sandbox Code Playgroud)
这些基本上是一样的,只是略有不同的方式.
这是另一个与原始版本更接近的选项:
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 };
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4670 次 |
最近记录: |