Search code examples
c#selenium-webdriverforeachiteratorauto

Autocreate nested foreach statement


I have a simple scenario I am trying to workout which involves auto creating nested foreach statements. What the method is to do is take the int value passed into the method and based on this, it should automatically create nested foreach statements.

public static String[] ValuesAdd1 = { "a", "b", "c" };
public static String[] ValuesAdd2 = { "1", "2", "3" };
static int count = 2;

    public void ConutNumber(int count)
    {
        count = Program.count;
        if (count.Equals(""))
        {
            Console.WriteLine("Empty element, please add");
        }
        else
        {
            //create nested foreach statement using count value
            Console.WriteLine(count);
            Console.ReadLine();
        }
    }

An example is this, as above the element is 2, therefore a total of nested 2 foreach statements should be created looking like this:

foreach(var i in ValuesAdd1)
{
     foreach(var ii in ValuesAdd1)
     {
         Console.writeline(i, ii);
     }
}

I would appreciate your professional feedback.


Solution

  • If it isn't a requirement to keep the ValuesAddX separated, you could have an array of arrays, and foreach over that:

    public static string[][] ValuesAdd = 
        {
            new [] { "a", "b", "c" },
            new [] { "1", "2", "3" },
            new [] { "x", "y", "z" },
        };
    
    public void NestedForeach() 
    {
        // Note that count isn't required anymore as we're using
        // ValuesAdd.Length as the count
        NestedForeachRecursive(string.Empty, 0);
    }
    
    public void NestedForeachRecursive(string prefix, int depth)
    {
        foreach (var item in ValuesAdd[depth])
        {
            var nextDepth = depth + 1;
            var nextPrefix = prefix + item;
    
            if (nextDepth < ValuesAdd.Length)
                NestedForeachRecursive(nextPrefix, nextDepth);
            else
                Console.WriteLine(nextPrefix);
        }
    }
    

    Note that because you're iterating over every item for every other item, the performance of this will scale very poorly.

    The output of this example is:

    a1x
    a1y
    a1z
    a2x
    a2y
    a2z
    a3x
    a3y
    a3z
    b1x
    b1y
    b1z
    b2x
    ... and so on