ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetPermutations

GetPermutations

Source

public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> items) {
    if (items.Count() > 1) {
        return items.SelectMany(item => GetPermutations(items.Where(i => !i.Equals(item))),
                                (item, permutation) => new[] { item }.Concat(permutation));
    } else {
        return new[] { items };
    }
}

Example

var l = new List<int> { 1, 2, 3, 4 };

foreach (var item in l.GetPermutations()) {

    foreach (var value in item) {
        Console.Write(value);
        Console.Write(" ");
    }
    Console.WriteLine();
}

Author: Fons Sonnemans

Submitted on: 3 sep. 2013

Language: C#

Type: System.Collection.Generic.IEnumerable<T>

Views: 6095