Link to home
Start Free TrialLog in
Avatar of GouthamAnand
GouthamAnand

asked on

How to come out of foreach loop, when it is there inside of couple of foreach loops?

I have foreach loops as shown below.
foreach (InvoiceBO objInvoice in objEDIBO.InvoiceList)
            {
             // loop 1  
              foreach (InvoiceLineItemBO lineItem in objInvoice.LineItemDetailsList)
                {
                   // loop 2
                    foreach(ItemChargeDetailsBO chargeDetails in lineItem.ChargeDetailsList)
                    {
                     // loop 3
                    }
                }
            }

How to come out of only 3rd foreach loop but need to continue with other 2 foreach loops?

How to come out of 2nd foreach when it is inside of 3rd foreach loop, but should continue with the 1st foreach loop?

How to come out of all 3 foreach loops but should continue in within the same procedure?

Can anyone help me in this regard?
Avatar of Binuth
Binuth
Flag of India image

use

break;  keyword inside the loop
Avatar of Pratima
Try this

 lab1: ;
            foreach (InvoiceBO objInvoice in objEDIBO.InvoiceList)
            {
                // loop 1  
                lab2: ;
                foreach (InvoiceLineItemBO lineItem in objInvoice.LineItemDetailsList)
                {
                    // loop 2
                     lab3: ;
                    foreach (ItemChargeDetailsBO chargeDetails in lineItem.ChargeDetailsList)
                    {
                       goto  lab1;
                    }
                }
            }

Change goto  lab1; as per your requirement
Try this code.

Set the appropriate value of variable 'brkType' to break out of the appropriate code.
enum BreakType
{
    LOOP1,
    LOOP2,
    LOOP3,
    NONE
}
 
BreakType brkType = BreakType.NONE;
 
foreach (InvoiceBO objInvoice in objEDIBO.InvoiceList)
{
 // loop 1  
  foreach (InvoiceLineItemBO lineItem in objInvoice.LineItemDetailsList)
    {
       // loop 2
        foreach(ItemChargeDetailsBO chargeDetails in lineItem.ChargeDetailsList)
        {
	    //loop 3
            // To Break out of the respective loop set the appropriate value here
	    brkType = BreakType.LOOP3;
	    break;
        }
	
        if (brkType == BreakType.LOOP2)
			break;
    }
    if (brkType == LOOP1)
		break;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CuteBug
CuteBug
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GouthamAnand
GouthamAnand

ASKER

Thank you...