c# foreach loop list code example
Example 1: c# loop through list
using System;
using System.Collections.Generic;
namespace forgetCode {
class program {
public static void Main() {
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
foreach (int item in list) {
Console.WriteLine(item);
}
for (int i = 0; i < list.Count; i++) {
Console.WriteLine(list[i]);
}
}
}
}
Example 2: 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 3: get out of foreach statement c#
foreach (string s in sList)
{
if (s.equals("ok"))
{
break;
}
}
Example 4: c# list foreach
someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); });