Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot we use break statement in a lambda(C#3.0)

Tags:

c#-3.0

Consider this

List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6 };

            int j = 0;
            intList.ForEach(i =>
                {
                    if (i.Equals(1))
                    {
                        j = i;
                        break;
                    }
                }
            );

Throwing error: No enclosing loop out of which to break or continue

But the below works

foreach(int i in intList)
{
j = i; break;
}

Why so. Am I making any mistake.

Thanks

like image 899
Newbie Avatar asked Jan 22 '23 01:01

Newbie


1 Answers

Keep in mind that the purpose of the ForEach method is to call the lambda method you pass to it on each item in the list. If you need to break out of a loop as part of your loop processing, you have to use a classic loop.

like image 178
Randolpho Avatar answered Mar 11 '23 16:03

Randolpho