I have ideea: use expression trees to dynamically generate code that does what you need:
Here is the complete solution:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace testProjectExpressions { class Program { static void Main(string[] args) { List<int> lst1 = new List<int>() { 1, 2, 3 }; List<int> lst2 = new List<int>() { 4, 5, 6 }; List<int> lst3 = new List<int>() { 7, 8 }; var fnc = CartesianProduct<int>(3); var res = fnc(new[] {lst1, lst2, lst3 }); foreach (var product in res) { for (int index = 0; index < product.Length; index++) { var productVar = product[index]; if (index < product.Length - 1) Console.Write(productVar + ","); else { Console.WriteLine(productVar); } } } Console.ReadKey(); } private static Func<List<T>[], List<T[]>> CartesianProduct<T>(int howMany) { var inputArrayOfLists = Expression.Parameter(typeof (List<T>[]), "inputArgument"); ParameterExpression[] loopVariables = new ParameterExpression[howMany]; for (int index = 0; index < howMany; index++) if (loopVariables[index] == null) loopVariables[index] = Expression.Variable(typeof (T)); List<Expression> finalStatements = new List<Expression>();
source share