代码之家  ›  专栏  ›  技术社区  ›  user726720

跳过foreach循环中的'n'迭代

  •  0
  • user726720  · 技术社区  · 7 年前

    n 每个循环中的迭代次数。

    下面是一个例子。在if条件下,将涉及超过1个节点。这些节点应该从foreach循环中省略。例如,在if语句中涉及3个节点,我需要foreach循环跳到下一次迭代的第4个节点。

    foreach (XmlNode node in docs.SelectNodes(query))
    {
       if (condition = true)
        {
    
           do
            {
    
               XmlNode nextnode = parentnode.NextSibling;
               string nextnodetest = nextnode.LocalName;
               if (nextnodetest = "Programme")
               {
                //calculate duration.
                }
           while (nextnodetest !=programme)
    
          }
        // skip the nodes in the foreach loop that were involved in the if/do statements above
    }
    

    3 回复  |  直到 7 年前
        1
  •  1
  •   DisplayName    7 年前

    也许是这样的

            XmlNodeList nodeList = docs.SelectNodes(query)
            XmlNode node;
            for (int i = 0; i < nodeList.Count; i++)
            {
                node = nodeList[i];
                if (condition == true)
                {
    
                    int itemsToSkip = 0;
                    string nextnodetest;
                    do
                    {
                       ...
    
                        if (nextnodetest == "Programme")
                        {
                            itemsToSkip++;
                            //calculate duration.
                        }
                    } while (nextnodetest != "Programme");
    
                    i = i + itemsToSkip;
                }
    
                ... your code 
            }
    
        2
  •  1
  •   Saeed Bolhasani    7 年前

    请尝试以下代码:

    var nodes = docs.SelectNodes(query).OfType<XmlNode>().ToArray();
    for (int i=0; i< nodes.Length; i++)
    {
        if(condition....)
        {
          ....
          i+= n;
        }
    
    }
    
        3
  •  0
  •   jdweng    7 年前

    var nodes = docs.SelectNodes(query).ToList();
    for(int i = 0; i < nodes.Count; i += n)
    {
       XmlNode node = nodes[i];
    }