Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double foreach break with a "If" statement? [duplicate]

Tags:

c#

foreach

Possible Duplicate:
Breaking out of a nested loop

I got somthing like (to simplify)

foreach (...)
{
    foreach (...)
    {
        //Some code

        if (statement)
        {
            break;
        }
    }
}

The thing is that I want my statement to leave for the double-foreach loop ! I'm thinking about a sort of "break flag" as a boolean but is there any way to avoid that ?

like image 368
Guillaume Slashy Avatar asked Nov 16 '11 11:11

Guillaume Slashy


3 Answers

You could avoid the nested loop entirely by using Linq and SelectMany.

Instead of:

foreach(var value in someValues)
{
    foreach(var subValue in value.SubValues)
    {
        // ...
        break;
    }
}

Your code would become:

foreach(var subValue in someValues.SelectMany(v => v.SubValues))
{
    // ...
    break;
}

If you need some logic to select whether or not you loop over SubValues, throw that logic in an additional Where clause.

Instead of

foreach(var value in someValues)
{
    if(value.IsMumsHairGreenToday)
    {
        foreach(var subValue in value.SubValues)
        {
            // ...
            break;
        }
    }
}

You can write:

var subValues = someValues
    .Where(v => v.IsMumsHairGreenToday)
    .SelectMany(v => v.SubValues)
    ;

foreach(var subValue in subValues)
{
    // ...
    break;
}
like image 66
Merlyn Morgan-Graham Avatar answered Oct 24 '22 10:10

Merlyn Morgan-Graham


You may use goto.

like image 37
KV Prajapati Avatar answered Oct 24 '22 09:10

KV Prajapati


Sure, you should check goto.

like image 31
DanielB Avatar answered Oct 24 '22 11:10

DanielB