Reputation: 2296
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.
Upvotes: 0
Views: 867
Reputation: 3256
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
Upvotes: 2
Reputation: 246
You should use recursion:
public void ConutNumber(int count)
{
...
GoThroughElements(count);
...
}
public void GoThroughElements(int count, List<String> recurseValues = new List<String>())
{
foreach(String value in ValuesAdd1)
{
recurseValues.Add(value);
if(count == 1)
{
// In deepest recursion iterate through the line of values
foreach(String i in recurseValues)
Console.WriteLine(i);
}
else if(count > 1)
{
GoThroughElements(--count, recurseValues);
}
else
{
throw new Exception("Wrong count!");
}
}
}
Don't forget to check your count for invalid values. Use recursion with great care, it may easily cause memory issues if a wrong case goes unnoticed.
Upvotes: 2