foreach list c# code example

Example 1: foreach syntax 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 2: how do i foreach c#

//No counter just the foreach.
 //the HelloWorld is the Class objects name nor a public string can be used aswell.
foreach (string element in fibNumbers)
{
    Console.WriteLine(element.HelloWorld);
}

Example 3: The foreach Loop c#

string[] names = {"William.", "James", "Oliver", "Lucas"};
foreach (string i in names) 
{
  Console.WriteLine(i);
}

Example 4: c# list foreach

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

Example 5: c# list.foreach

List<string> someList = <some way to init>
someList.ForEach(delegate(string s) {
    <process the string>
});