tags:

views:

73

answers:

1

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.

+9  A: 

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 };
Jon Skeet
Wow, those are awesome! Much easier now, thank you very much! By the way, in your second query, your `Select` is missing an open parenthesis on the lambda arguments.
nasufara
@nasufara: Fixed, thanks.
Jon Skeet