使用匿名委托时.ForEach循环;如何退出列表<串GT? [英] How do i exit a List<string>.ForEach loop when using an anonymous delegate?
问题描述
在一个正常的循环,你可以打出来用break一个循环。可以与使用匿名委托办?
In a normal loop you can break out of a loop using break. Can the same be done using an anonymous delegate?
为例
inputString和结果都是委托外部声明。
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
}
}
));
编辑:
感谢您的答复,我其实在一分钟读你的书约翰:)只是为了记录我打这个问题和切换回正常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).
在你的榜样,但是,<一个HREF =http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx> 列表< 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.
这篇关于使用匿名委托时.ForEach循环;如何退出列表<串GT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!