Can we use break statement in lambda (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; } } ); 

Throw error: There is no closed loop from which you can break or continue

But below works

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

Why is that. I am wrong.

thanks

+4
source share
5 answers

Keep in mind that the purpose of the ForEach method is to call the lambda method, which you pass to it for each element in the list. If you need to break out of a loop as part of your loop handling, you need to use a classic loop.

+6
source

Due to the fact that you are changing โ€œbeyond the scope of the question,โ€ I am going to ask what exactly the OP is trying to accomplish.

This code tries to determine if an integer (1) exists anywhere in the list. But it seems clear to me that the above code is just a demo, not a real problem.

Using "ForEach" to iterate through a list to determine if something in the list is the wrong way around this. Instead, using one of the many Find features is a better approach.

For example, with the original OP code:

  j = intList.Find(i => i.Equals(1)); 

This will do the same as the above proposed code. It will iterate over the list by list (and, if possible), return the lambda value to "j" and break earlier.

  intList.Exists(i => i.Equals(1)); 

Will do the same effectively. It will iterate over the list and return TRUE if it can find if 1 exists and break before. (otherwise, iterates over the entire list and returns FALSE.)

  intList.FindIndex(i => i.Equals(1)); 

Will return the FIRST index position that matches the lambda. (again, if possible, early early)

  intList.FindAll(i => i.Equals(1)); 

Returns an auxiliary list of all elements in intList that match the lambda expression. (Naturally, you need to iterate over the entire list, regardless ...)

Newbie: Is there a reason you cannot use any of these built-in methods? Just curious how I would like to help.

Greetings.

+3
source

The ForEach method is not a real ForEach loop. You can simulate the effect by throwing an exception inside the lambda and catching it outside the ForEach call.

0
source

The break statement only works in the same function area as the foreach statement. Lambda launches a new area of โ€‹โ€‹functions, so the gap does not work.

0
source

You can use the extension methods SkipWhile() and Take() to mimic what you are doing, but this is not good or readable ...

 public void SO2857489() { var intList = new List<int> {1, 2, 3, 4, 5, 6}; var j = 0; intList.SkipWhile(i => i != 1).Take(1).ToList().ForEach(i => j = i); Console.WriteLine(j); } 

Here SkipWhile() does the work of your if (i.Equals(1)) , and Take(1) does the break job. As I said, this is ugly.

0
source

Source: https://habr.com/ru/post/1310114/


All Articles