Select all unique combinations of a single list, with no repeats, using LINQ

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

Is it possible to convert these two for loops to LINQ?

Thanks.


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

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 };
链接地址: http://www.djcxy.com/p/22914.html

上一篇: 检查路径是文件还是目录的更好方法?

下一篇: 使用LINQ选择单个列表的所有唯一组合,无重复