I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many
var numbers = new[] { 2, 3, 4, 3, 4, 3, 3, 4, 2, 4, 4, 3, 4 };
var result = (numbers.Select(i => Enumerable.Range(0, i))).CartesianProduct();
Using the extension method at http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
public static IEnumerable> CartesianProduct(this IEnumerable> sequences)
{
// base case:
IEnumerable> result =
new[] { Enumerable.Empty() };
foreach (var sequence in sequences)
{
// don't close over the loop variable (fixed in C# 5 BTW)
var s = sequence;
// recursive case: use SelectMany to build
// the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] { item });
}
return result;
}