foreach string c# code example

Example 1: get out of foreach statement c#

foreach (string s in sList)
{
    if (s.equals("ok"))
    {
        break; // get out of the loop
    }
}

Example 2: c# list foreach

someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); });

Example 3: foreach c#

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Example 4: 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);
}