打破了一个嵌套循环 [英] Breaking out of a nested loop

查看:105
本文介绍了打破了一个嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个循环是嵌套在另一个,我怎么能有效地来到两个回路(内部和外部)在最快的方式呢?

If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?

我不想不得不使用一个布尔值,然后不得不说去别的方法,而只是向外环后执行code的第一行。

I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.

什么是要对这个快速和不错的方式?

What is a quick and nice way of going about this?

感谢

我在想,例外的是不便宜/只应在一个真正的特殊条件等被抛出因此,我不认为这解决办法是从性能角度不错。

I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.

我不觉得这是正确的采取的新功能的优势,。NET(匿名方法)做的东西是pretty根本。

I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.

正因为如此,tvon(抱歉不能拼出完整的用户名!)有一个很好的解决方案。

Because of that, tvon (sorry can't spell full username!) has a nice solution.

马克:很高兴使用匿名方式,这也太是伟大的,但因为我可能是一份工作,我们不使用一个版本的.NET / C#,支持匿名方法,我需要知道传统的方法太

Marc: Nice use of anon methods, and this too is great but because I could be in a job where we don't use a version of .NET/C# that supports anon methods, I need to know a traditional approach too.

推荐答案

好了,GOTO,但是这是丑陋的...而不是总是可能的。您还可以将循环进入一个方法(或匿名方法),并使用回归退出返回到主code。

Well, "goto", but that is ugly... and not always possible. You can also place the loops into a method (or an anon-method) and use "return" to exit back to the main code.

        // goto
        for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 100; j++)
            {
                goto Foo; // yeuck!
            }
        }
    Foo:
        Console.WriteLine("Hi");

        // anon-method
        Action work = delegate
        {
            for (int x = 0; x < 100; x++)
            {
                for (int y = 0; y < 100; y++)
                {
                    return; // exits anon-method
                }
            }
        };
        work(); // execute anon-method
        Console.WriteLine("Hi");

这篇关于打破了一个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆