开发者

How to break out of an inner loop back to an outer loop?

I have 4 entities"

ObjectA, ObjectB, ObjectC, ObjectD

foreach(ObjectA objectA in listObjectA)
if (relationAB)
  foreach(ObjectB objectB in listObjectB) 
  if (relationBC)   
    foreach(ObjectC objectC in listObjectC) 
    if (relationCD)   
      foreach(ObjectD objectD in listObjectD) 
        if (I found what I'm looking for)  
        Do something

So开发者_开发问答, when I will found what I wass looking for, I want to go to the first line, to the first for, but to the second element from the list. How can I do this? Whit goto?

Later Edit: This question is for C#.

P.S. Could you think a better way to do what I'm trying to do, whithout using 4 fors?


Well, since this is just a "programming languages" question, the general answer would be to use your language's facility for naming loops, and then put the proper name on the "break" statement.

Sadly, I don't think the current versions of C and C++ support such a thing, so you would indeed have to resort to a goto when using them. A good way to avoid that would be to put the loop you want to break out of into its own subroutine, and just do a return when you are done instead of a break. That's what I generally do when working in those poor languages.

Your revised example would be:

void find_whatever (/* probably pass in the lists or objects to search for*/)
  foreach(ObjectA objectA in listObjectA)
    if (relationAB)
      foreach(ObjectB objectB in listObjectB) 
        if (relationBC)   
          foreach(ObjectC objectC in listObjectC) 
            if (relationCD)   
              foreach(ObjectD objectD in listObjectD) 
                if (I found what I'm looking for)  
                Do something
                return;

Note: The tag was changed from "programming languages" to "C#". That was the right thing to do for the question, but a lot of people liked this answer so I'm not making major mods to it.


Depending on the language, you can generally add break labels. I'd avoid this, however, and suggest the following:

function main() {
    foreach (ObjectA a in listA) {
        if (relationAB) {
            processA(a)
        }
    }
}

function processA(ObjectA a) {
    foreach (b) {
        foreach (c) {
            foreach (d) {
                if (found) {
                    doSomething();
                    return;
                }
            }
        }
    }
}

It can be hard to read code that has break labels and gotos. Breaking it into functions can make it easier to read and (probably) easier to write and debug.


The simplest option is to put it all in a function and use the return statement instead of the break statement.


Better to use return in such cases.

Just put some of your inner for in a method and return from it when necessary. It will be much more readable then a chain of

if (found) {
 break;
}

inside your loops.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜