dotnetdev dotnetdev - 1 year ago 60
C# Question

Breaking out of a nested loop

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?

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.

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.

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

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.

Answer Source

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!

        // 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download