Yes, you can use the iterator variable anywhere within the body of the foreach
loop even if that that loop contains another loop:
foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
{
foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
{
if ((int)val > 10)
{
Console.WriteLine("{0} of {1}", val, val1);
}
else
{
Console.WriteLine("{0} of {1}", (int)val, val1);
}
}
}
Now, if you want to rewrite this so that all the 2's will be printed at together, and then the 3's, and so on, just swap the loops:
foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
{
foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
{
if ((int)val > 10)
{
Console.WriteLine("{0} of {1}", val, val1);
}
else
{
Console.WriteLine("{0} of {1}", (int)val, val1);
}
}
}
And to write them in a row, you can use Write
instead of inside the loop to keep each value together, then WriteLine
outside the loop to separate that row from the next:
foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
{
foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
{
if ((int)val > 10)
{
Console.Write("{0} of {1}", val, val1);
}
else
{
Console.Write("{0} of {1}", (int)val, val1);
}
}
Console.WriteLine();
}