1
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
    return k == 0 
        ? new[] { new T[0] } 
        : elements.SelectMany((e, i) => elements
              .Skip(i + 1).Combinations(k - 1)
              .Select(c => (new[] { e }).Concat<T>(c)));
    }

The code currently runs combination of strings in series e.g list of a,b,c in two ways would give ab,ac,bc which is very correct. Is there a way I can modify the code to run the combination in parallel (i.e to max my cpu processor) because I intend to run combination on large volume of strings.

Tamás Szabó
  • 1,388
  • 11
  • 23

1 Answers1

0

This should introduce some parallelism. Note in particular the AsParallel.

public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
    return k == 0 ? (IEnumerable<IEnumerable<T>>)new[] { new T[0] } : elements.AsParallel().SelectMany((e, i) => elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat<T>(c)));
}

You could also consider using Enumerable.Empty rather than new T[0].

mjwills
  • 23,389
  • 6
  • 40
  • 63