C#退出使用lambda的泛型ForEach
有谁知道是否可以退出使用 lambda 的通用 ForEach?例如,
someList.ForEach(sl =>
{
if (sl.ToString() == "foo")
break;
// continue processing sl here
// some processing code
}
);
这段代码本身无法编译。我知道我可以使用常规的 foreach,但为了保持一致性,我想使用 lambda。
非常感谢。
Does anyone know if it is possible to exit a generic ForEach that uses lambda? e.g.
someList.ForEach(sl =>
{
if (sl.ToString() == "foo")
break;
// continue processing sl here
// some processing code
}
);
This code itself won't compile. I know I could use a regular foreach but for consistency I want to use lambda.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然。但首先请注意,我建议不要这样做;我说序列运算符不应该有副作用,而语句应该有副作用。如果您要在 ForEach lambda 中执行某些操作,请将其作为 foreach 循环体中的语句,而不是使其看起来像序列运算符。
也就是说,这就是你要做的。首先,您自己编写一个适用于任意序列而不仅仅是列表的 ForEach:
现在您可以像这样编写中断:
Sure. But first, note that I recommend against this; I say that a sequence operator should not have a side effect, and a statement should have a side effect. If you're doing something in that ForEach lambda, then make it a statement in the body of a foreach loop rather than making it look like a sequence operator.
That said, here's what you do. First, you write yourself a ForEach that works on arbitrary sequences, not just lists:
And now you write your break like this:
来自 MSDN
不知道您发布的代码是否有帮助。相关引用来自MSDN文章末尾。
From MSDN
Don't know if that helps given the code you posted. The relevant quote is from the end of the MSDN article.
警告:以下代码仅供娱乐,请勿认真对待!
您可以像这样“模拟”提前返回的继续:
也就是说,我认为 lambda 内的副作用表明您做错了。请改用适当的 foreach。或者像 TakeWhile 这样的东西,正如 Eric 已经善意地演示的那样。
Warning: the code below is not to be taken seriously and is provided for entertainment purposes only!
You can 'simulate' a continue with an early return like this:
That said, I think that side effects within lambda's are a sign that you're doing it wrong. Use a proper foreach instead. Or something like TakeWhile, as Eric kindly demonstrated already.
这个怎么样?
How about this?