Reduce confusion (?) IEnumerable using common versions of IEnumerable and IEnumerator .
The enumerated permutation is IEnumerable<IEnumerable<T>> . So you might have something like
IEnumerable<IEnumerable<T>> GetPermutations(IEnumerable<T> sequence) { return new Permuter<T>(sequence); }
and
public class Permuter<T> : IEnumerable<IEnumerable<T>> { ... }
In addition, I saw more than one case where one type implemented both IEnumerable<T> and IEnumerator<T> ; his GetEnumerator method was simply return this; .
I think this type should be a structure, though, because if it were a class, you would have all kinds of problems if you called GetEnumerator () a second time before the first enumeration is completed.
EDIT: using permutation
var permuter = GetPermutations(sequence); foreach (var permutation in permuter) { foreach (var item in permutation) Console.Write(item + "; "); Console.WriteLine(); }
Assuming the input sequence is {1, 2, 3}, the output
1; 2; 3; 1; 3; 2; 2; 1; 3; 2; 3; 1; 3; 1; 2; 3; 2; 1;
EDIT:
Here's a super-ineffective implementation to illustrate the sentence:
public class Permuter<T> : IEnumerable<IEnumerable<T>> { private readonly IEnumerable<T> _sequence; public Permuter(IEnumerable<T> sequence) { _sequence = sequence; } public IEnumerator<IEnumerable<T>> GetEnumerator() { foreach(var item in _sequence) { var remaining = _sequence.Except(Enumerable.Repeat(item, 1)); foreach (var permutation in new Permuter<T>(remaining)) yield return Enumerable.Repeat(item, 1).Concat(permutation); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
phoog source share