【问题标题】:How to use reverse in foreach of XmlNodeList?如何在 XmlNodeList 的 foreach 中使用反向?
【发布时间】:2013-07-17 01:26:22
【问题描述】:

我想从foreach逆向获取数据

这里XmlNodeList comments = d.SelectNodes("//comments/comment/creator");

我有 4 个值,我想反转它

我已经写了这段代码

 public void commentM4(string pstId, string cmtId)
    {
        XmlDocument d = new XmlDocument();
        d.LoadXml(content);

        XmlNodeList comments = d.SelectNodes("//comments/comment/creator");
        foreach (XmlNode xncomment in  comments)
        {
            commentMemberId = xncomment["id"].InnerText;
            DbConnection.Open();
            DbCommand = new OleDbCommand("select count(response_id) from  mw_response where customer_id = '" + commentMemberId + "' AND post_id='" + pstId + "'", DbConnection);
            OleDbDataReader DbReader = DbCommand.ExecuteReader();

            while (DbReader.Read())
            {
                count = DbReader[0].ToString();
                cnt = Convert.ToInt32(count);
                if ((cnt == 0) && (comments1 != ""))
                {
                    DbCommand = new OleDbCommand("update mw_response set prod_id = (select prod_id from mw_post where post_id='" + pstId + "'),customer_id = (select customer_id from mw_customer where customer_id='" + commentMemberId + "') where response_id = '" + cmtId + "'", DbConnection);
                    DbCommand.ExecuteNonQuery();
                }
            }
            DbReader.Close();
            DbConnection.Close();
        }
    }

有什么想法吗?提前致谢。

【问题讨论】:

    标签: c# asp.net xml-parsing foreach


    【解决方案1】:

    改用for 循环,从最后一个元素开始,然后返回到第一个元素。

    if (comments.Count > 0)
    {
        for (int i = (comments.Count - 1); i >= 0; i--)
        {
         XmlNode xncomment = comments[i];
        //Rest of the logic...
        }
    }
    

    更新:我添加了一个 if 块以确保循环仅在集合中有多个元素时运行。

    【讨论】:

      【解决方案2】:

      这可以帮助你:

      公共静态字符串 ReverseString(string s) { char[] arr = s.ToCharArray(); Array.Reverse(arr); 返回新字符串(arr); }

      【讨论】:

      • OP 不适用于字符串或数组。他有一个 XmlNodeList,它没有 ToArray() 方法。此外,为此目的编写一个只调用另一个方法的方法似乎有点过头了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      相关资源
      最近更新 更多