CartesianProduct

Cartesian, if you don’t know what it is, please google it by yourself.

Thank you for reading.

 

        public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
        {
            //This is the normal way
            IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
            foreach (var sequence in sequences)
            {
                var localSequence = sequence;
                result = result.SelectMany(
                  _ => localSequence,
                  (seq, item) => seq.Concat(new[] { item })
                );
            }
            return result;

            //This is the linq way
            //IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
            //return sequences.Aggregate(
            //  emptyProduct,
            //  (accumulator, sequence) =>
            //    from accseq in accumulator
            //    from item in sequence
            //    select accseq.Concat(new[] { item }));
        }

Comments are closed.