Reputation: 3
I have been trying to get my head around this but it hasn't been working:
I've gotten this function from http://fir3pho3nixx.blogspot.com/2011/01/recursion-cross-product-of-multiple.html where it returns a list but I can't seem to read the values within each object in the list.
Here is the function in question:
private static List<object> GetCrossProduct(object[][] arrays)
{
var results = new List<object>();
GetCrossProduct(results, arrays, 0, new object[arrays.Length]);
return results;
}
private static void GetCrossProduct(ICollection<object> results, object[][] arrays, int depth, object[] current)
{
for (var i = 0; i < arrays[depth].Length; i++)
{
current[depth] = arrays[depth][i];
if (depth < arrays.Length - 1)
GetCrossProduct(results, arrays, depth + 1, current);
else
results.Add(current.ToList());
}
}
Upvotes: 0
Views: 121
Reputation: 493
You are having problem because you are probably expecting a linear List
, when it is actually a List
of List
s.
To access elements within your result, you need to do something like this:
var resultingList = GetCrossProduct(blargh); // where blargh is the array you passed in
foreach (IList<object> innerList in resultingList)
{
foreach (var listValue in innerList)
{
// listValues should be the individual strings, do whatever with them
// e.g.
Console.Out.WriteLine(listValue);
}
}
The reason for this is because of the line:
results.Add(current.ToList());
Which creates a new list and adds it to the result list.
Upvotes: 1