How to encode dynamic levels for a loop?

My problem is this:

I need to list several lists, but the list numbers are unrecognizable. And all item numbers in each list are also unrecognizable. Sicne I would like to go through all combinations of list items, for example: 1) select A from list 1, A from list 2, A from list 3; 2) ick A from list 1, A from list 2, B from list 3 ... to rearrange ALL.

I use inested for-loop to move, for example, if I have two lists, then:

        for (int i = 0; i < list[0].EnergyParameters.ListEnergyLevelCandidates.Count; i++)
        {
            for (int j = 0; j < list[1].EnergyParameters.ListEnergyLevelCandidates.Count; j++)
            {
                // Do sth
            }
        }

If I have three lists, then:

        for (int i = 0; i < list[0].EnergyParameters.ListEnergyLevelCandidates.Count; i++)
        {
            for (int j = 0; j < list[1].EnergyParameters.ListEnergyLevelCandidates.Count; j++)
            {
                for (int k = 0; k < list[2].EnergyParameters.ListEnergyLevelCandidates.Count; k++)
                {
                    // Do sth
                }
            }
        }

Since the list numbers are unrecognizable, therefore, the number of slots is unrecognizable, which means that I do not know how many levels of the for loop should be written.

Within this kind of circumstance, how can I write code for dynamic levels for a loop? I do not want to write 10 cycles for 10 lists.

+5
1

, , : . , :

void AllCombos(List<string>[] lists, int level, string[] current) {
    if (level == lists.Length) {
        // Do somthing; items of current[] contain elements of the combination
    } else {
        foreach (var s in lists[level]) {
            current[level] = s;
             AllCombos(lists, level+1, current);
        }
    }
}

AllCombos :

var lists = new List<string>[10];
for (int i = 0 ; i != 10 ; i++) {
    lists[i] = PopulateMyList(i);
}
string[] current = new string[lists.Length];
AllCombos(lists, 0, current);
+10

All Articles