List ForEach break

2019-01-27 13:07发布

is there a way to break out of the foreach extension method? The "break" keyword doesn't recognize the extension method as a valid scope to break from.

//Doesn't compile
Enumerable.Range(0, 10).ToList().ForEach(i => { System.Windows.MessageBox.Show(i.ToString()); if (i > 2)break; });

Edit: removed "linq" from question


note the code is just an example to show break not working in the extension method... really what I want is for the user to be able to abort processing a list.. the UI thread has an abort variable and the for loop just breaks when the user hits a cancel button. Right now, I have a normal for loop, but I wanted to see if it was possible to do with the extension method.

标签: c# foreach break
8条回答
你好瞎i
2楼-- · 2019-01-27 14:00

I recommend using TakeWhile.

Enumerable.Range(0, 10).TakeWhile(i => i <= 2).ToList().ForEach(i => MessageBox.Show(i.ToString()));

Or, using Rx:

Enumerable.Range(0, 10).TakeWhile(i => i <= 2).Run(i => MessageBox.Show(i.ToString()));
查看更多
SAY GOODBYE
3楼-- · 2019-01-27 14:07

Why not use Where?

Enumerable.Range(0, 10).Where(i => i <= 2).ToList().ForEach(...)
查看更多
登录 后发表回答