0

I just stumbled over a problem while programming which would really benefit from a goto like structure. Consider this example:

//tries to find a solution for a problem 3 times
//in this process copies elements from old to newList
foreach (var tryNbr in Util.range(0,3)) 
{
    List<A> newList = new List<A>();
    List<A> oldList = workList;
    while(oldList.Count != 0)
    {
        List<A> possibleMatched = FINDWITHLINQSTUFF;
        //try stuff out

        if(possibleMatches.Count == 0)
            break;

        //do more stuff
    }

    if(oldList.Any())
    {
        workList = newList;
        return true;
    }
}

So the problem i have here is, that in my while loop, i need to check for some condition, and if it is true i want to continue from the next foreach iteration, since my whole previous process did not work also.

Since neighter break or continue can do this, i need to check for an extra condition behind my while, which is pretty prone to errors, if i might change something later without giving the attention needed.

Is there a contruct like

goto foreach;

or

continue foreach;

Which continues from the next outer foreach loop? Would it actually be a viable solution to use a goto here (and incrementing the counter manually?

PS: Do you have a better solution for the general structure of this Code?

4

1 回答 1

1

如果 while 循环的结果应该控制(即继续)foreach 循环,请将其设计为:

bool WhateverMethod() 
{

    //tries to find a solution for a problem 3 times
    //in this process copies elements from old to newList
    foreach (var tryNbr in Util.range(0,3)) 
    {
        List<A> newList = new List<A>();
        List<A> oldList = workList;

        if (Matched(oldList, newList))
            continue;

        if(oldList.Any())
        {
            workList = newList;
            return true;
        }
    }
}

bool Matched(List<A> oldList, List<B> newList)
{
   while(oldList.Count != 0)
    {
        List<A> possibleMatched = FINDWITHLINQSTUFF;
        //try stuff out

        if(possibleMatches.Count == 0)
            return false;

        //do more stuff
    }

    return true; // I'm assuming?
}

这并没有解决 goto 的用法,或者“它总是邪恶的”这个问题,但我建议 goto 是“总是”或“几乎总是”不必要的。

于 2016-03-17T17:01:07.497 回答