C# Cartesian product

Date: 2025-03-31
public static IEnumerable<IEnumerable<T>> Cartesian<T>(IEnumerable<IEnumerable<T>> sequences)
{
    return sequences.Aggregate(Enumerable.Repeat(Enumerable.Empty<T>(), 1), (accumulator, sequence) => accumulator.SelectMany(acc => sequence.Select(item => acc.Append(item))));
}


public static IEnumerable<IEnumerable<T>> CartesianRecursive<T>(IEnumerable<IEnumerable<T>> sequences)
{
    if (!sequences.Any())
    {
        yield return Enumerable.Empty<T>();
        yield break;
    }

    var firstSet = sequences.First();
    var remainderSets = CartesianRecursive(sequences.Skip(1));

    foreach (var item in firstSet)
    {
        foreach (var remainder in remainderSets)
        {
            yield return new[] { item }.Concat(remainder);
        }
    }
}
93800cookie-checkC# Cartesian product