Thomas Wiborg
Thomas Wiborg

Reputation: 15

Jump out from Inner-Foreach to Outer-Foreach, Keep Inner-Foreach where you left it

I have the following code:

foreach (XNode rowXml in elements.Nodes())
                         {        
                             foreach (DataRow rowDB in dataSetDB.Tables[0].Rows)
                             {
                                 string itemDB = rowDB[0].ToString().ToUpper();
                                 string itemXml = rowXml.ToString().ToUpper();
                                 if (itemDB == itemXml)
                                 {    
                                    //If itemDB == itemXml; jump to Outer_Foreach
                                 }
                                 if (itemDB != itemXml)
                                 {  
                                     //If itemDB != itemXml; jump to Outer_Foreach
                                 }
                             }

How is it possible to get out of Inner-Foreach and up to Outer-Foreach, and still keep both foreach where you left it. I am looping through a DB and XML table rows. Break; completley jumps out of the Inner-Foreach and im not able to catch where I left it, so I start back on index[0], when I loop through it over and over again.

Upvotes: 0

Views: 180

Answers (2)

Daan Timmer
Daan Timmer

Reputation: 15067

This answer is stolen from this answer here. What you want to achieve is a zip operation. For more information see the answer that I linked.

var xmlNodes = elements.Nodes();
var dbNodes = dataSetDB.Tables[0].Rows;

var xmlAndDB = xmlNodes.Zip(dbNodes , (x, d) => new { xNode = x, dNode = d });

foreach(var xd in xmlAndDB )
{
    Console.WriteLine(xd.xNode + xd.dNode);

    string itemDB = xd.dNode[0].ToString().ToUpper();
    string itemXml = xd.xNode.ToString().ToUpper();

    if (itemDB == itemXml)
    {    
        //If itemDB == itemXml;
    }
    else /* if (itemDB != itemXml) */ 
    {  
        //If itemDB != itemXml;
    }
}

Upvotes: 0

Tomzan
Tomzan

Reputation: 2818

It sounds like you need 'for' loop.

 int i = 0;
 int k = 0;
 bool shouldBreak;

 var nodes = elements.Nodes();
 var rows = dataSetDB.Tables[0].Rows;

 for (i = 0; i < nodes.Count(); i++)
 {
     for(k = 0; k < rows.Count(); k++)
     {
        string itemDB = rows[k][0].ToString().ToUpper();
        string itemXml = nodes[i].ToString().ToUpper();
            if (itemDB == itemXml)
            {   
                shouldBreak = true;
                break;
            }
            if (itemDB != itemXml)
            {  
                shouldBreak = true;
                break;
            }
     }
     if (toBreak)
         break;
 }

Now if you'll break the inner loop can know where it broke by accessing i and k

Upvotes: 1

Related Questions