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 循环?


- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01