Answers for "c# break from foreach method"

C#
31

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}");
Posted by: Guest on January-18-2020
4

get out of foreach statement c#

foreach (string s in sList)
{
    if (s.equals("ok"))
    {
        break; // get out of the loop
    }
}
Posted by: Guest on May-25-2020
0

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.
}
Posted by: Guest on January-06-2021

C# Answers by Framework

Browse Popular Code Answers by Language