【问题标题】:Select all unique combinations of a single list, with no repeats, using LINQ使用 LINQ 选择单个列表的所有唯一组合,不重复
【发布时间】:2011-03-29 15:25:06
【问题描述】:

我有一个数字列表,我需要使用 LINQ 查询创建列表中数字的每个可能的唯一组合,不重复。因此,例如,如果我有 { 1, 2, 3 },则组合将是 1-21-32-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...
    }
}

是否可以将这两个for 循环转换为 LINQ?

谢谢。

【问题讨论】:

  • 组合总是有序的,对吧?

标签: c# linq


【解决方案1】:

当然 - 您可以通过对 SelectMany 的一次调用和对 Skip 的嵌入式调用来完成:

var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
                               (first, second) => new { first, second });

这是一个替代选项,它不使用相当这样深奥的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 };

它们的作用基本相同,只是方式略有不同。

这是另一个更接近您的原始选项的选项:

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 };

【讨论】:

  • 关于深奥的第一个解决方案的讨论请参见:stackoverflow.com/questions/7991486/…
  • @David:我不相信 .NET 中的任何集合在多次迭代且之间没有变化时以不同的顺序返回元素。我们不在乎顺序是什么,只要它是一致的。
  • Dangit,那么我们在某个地方遇到了最奇怪的错误,谢谢,我将删除我的 2 个 cmets:p
  • @David:如果你能重现它,请务必创建一个新问题并用链接 ping 这个问题 :)
猜你喜欢
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多