Unique combinations of list

Try this:

void Main()
{
    var list = new List<string> { "a", "b", "c", "d", "e" };
    var result = GetPermutations(list, 3);
}

IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count)
{
    int i = 0;
    foreach(var item in items)
    {
        if(count == 1)
            yield return new T[] { item };
        else
        {
            foreach(var result in GetPermutations(items.Skip(i + 1), count - 1))
                yield return new T[] { item }.Concat(result);
        }

        ++i;
    }
}

For a count of 2 it returns this:

a, b
a, c
a, d
a, e
b, c
b, d
b, e
c, d
c, e
d, e

For a count of 3 it returns this:

a, b, c
a, b, d
a, b, e
a, c, d
a, c, e
a, d, e
b, c, d
b, c, e
b, d, e 
c, d, e

Is this what you expect?


The remaining items list in the implementation contains all items except the current starting item.

Get the items that are after the starting item instead:

IEnumerable<T> remainingItems = list.Skip(startingElementIndex + 1);

Instead of AllExcept, you should use a Subsequence that gives you only the items after the one you are considering.

Tags:

C#

Algorithm