using System; using System.Collections.Generic; using System.Linq; namespace Permutation { public static class Extension { public static IEnumerable> Permutations(this IEnumerable source) { if (source == null) throw new ArgumentNullException("source"); return PermutationsImpl(source, Enumerable.Empty()); } private static IEnumerable> PermutationsImpl(IEnumerable source, IEnumerable prefix) { if (!source.Any()) yield return prefix; foreach (var permutation in source.SelectMany(x => PermutationsImpl(source.Except(Yield(x)), prefix.Union(Yield(x))))) { yield return permutation; } } private static IEnumerable Yield(this T element) { yield return element; } } }