Assuming you mean itertools.product (it looks like it from the example given):
public static List< Tuple<T, T> > Product<T>(List<T> a, List<T> b)
where T : struct
{
List<Tuple<T, T>> result = new List<Tuple<T, T>>();
foreach(T t1 in a)
{
foreach(T t2 in b)
result.Add(Tuple.Create<T, T>(t1, t2));
}
return result;
}
n.b. struct
here means that T
must be a value type or a structure. Change it to class
if you need to throw in objects such as List
s, but be aware of potential referencing issues.
Then as a driver:
List<int> listA = new List<int>() { 1, 2, 3 };
List<int> listB = new List<int>() { 7, 8, 9 };
List<Tuple<int, int>> product = Product<int>(listA, listB);
foreach (Tuple<int, int> tuple in product)
Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);
Output:
1, 7
1, 8
1, 9
2, 7
2, 8
2, 9
3, 7
3, 8
3, 9
0
solved Product method in c#