string loop c# code example

Example 1: c# loop though array

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0

Example 2: c# iterate over string

// Regular Strings
string foo = "hello world", bar = string.Empty;

foreach(char c in foo){
    bar += c;
}

// StringBuilder
string foo = "hello world";
StringBuilder bar = new StringBuilder();

foreach (char c in foo)
{
    bar.Append(c);
}

Example 3: c# loop though array

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55