break List foreach loop in c# code example

Example 1: how to iterate tthrough a list in c#

static void Main()
{
  
  int[] someRandomList = new int[] {1, 2, 3, 4, 5};
  
  foreach (int number in someRandomList) 
  {
    Console.WriteLine(number);
  }
}

Example 2: c# break from foreach method

list.Foreach((item) => {
	// You cannot break from here beacuse of the structure of the method.
  	// Underneath is they way the meothd is tructured and a break is not allowed.
	//public static ForEach<T>(this IEnumerable<T> input, Action<T> action)
	//{
  	//foreach(var i in input)
    //	action(i);
	//}
});

// You have to convert your code into the traditional foreach:
foreach(var item in list) {
	// Your code here
  	break; // <- As you can see you can break here.
}