Try the following:
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 counting 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 counting 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, ec, d, e
Is that what you expect?
Daniel Hilgarth
source share