简体   繁体   中英

Getting a list of string values from this c# function:

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());
        }
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM