How do i exit a Listlt;stringgt;.ForEach loop when using an anonymous delegate?(使用匿名委托时如何退出 Listlt;stringgt;.ForEach 循环?)
问题描述
在正常循环中,您可以使用 break 跳出循环.使用匿名委托也可以做到这一点吗?
In a normal loop you can break out of a loop using break. Can the same be done using an anonymous delegate?
示例inputString 和 result 都在委托之外声明.
Example inputString and result are both declared outside the delegate.
blackList.ForEach(new Action<string>(
delegate(string item)
{
if(inputString.Contains(item)==true)
{
result = true;
// I want to break here
}
}
));
感谢您的回复,我实际上正在阅读您的书 John :) 只是为了记录,我遇到了这个问题并切换回正常的 foreach 循环,但我发布了这个问题,看看我是否遗漏了什么.
Thanks for the replies, I'm actually reading your book at the minute John :) Just for the record i hit this issue and switched back to a normal foreach loop but I posted this question to see if i missed something.
推荐答案
正如其他人所发布的,您无法在 ForEach 中退出循环.
As others have posted, you can't exit the loop in ForEach.
你会使用 LINQ 吗?如果是这样,您可以轻松地结合 TakeWhile 和自定义 ForEach 扩展方法(现在几乎每个项目似乎都有).
Are you able to use LINQ? If so, you could easily combine TakeWhile and a custom ForEach extension method (which just about every project seems to have these days).
但是,在您的示例中,List<T>.FindIndex 将是最好的选择 - 但如果您实际上并没有这样做,请发布您真正想要做的示例.
In your example, however, List<T>.FindIndex would be the best alternative - but if you're not actually doing that, please post an example of what you really want to do.
这篇关于使用匿名委托时如何退出 List<string>.ForEach 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用匿名委托时如何退出 List<string>.ForEach 循环?
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
