日期:2014-05-20  浏览次数:20433 次

.net后台简单问题
下面是我的代码:

  string html = "";
  xf.XfjService x = new xf.XfjService();
  string d = x.getXfj().@return;
  XmlDataDocument xd = new XmlDataDocument();
  XmlDocument dd = new XmlDocument();
  dd.LoadXml(d);
  XmlNodeList nodelist = dd.SelectNodes(@"/wsxf/xfjs/xfj");
  foreach (XmlNode n in nodelist)
  {
  string dz = n.Attributes["lj"].Value;
  html += "<p class='content'>";
  html += "<a target='_blank' href= '" + dz + "'>";
  html += "·<span>[网上信访]</span>";
  html += (n.ChildNodes[0].InnerText.ToString().Length <= 20 ? n.ChildNodes[0].InnerText.ToString() : n.ChildNodes[0].InnerText.ToString().Substring(0, 20) + "...");
  html += "</a></p>";
  }
  return html;

问题:foreach循环里面,现在nodelist有9条数据,但是我只想让它循环5次,怎么做?

------解决方案--------------------
int count = 0;
foreach(....)
{
if(count++== 5) break;


}
------解决方案--------------------
下面是我的代码:

string html = "";
xf.XfjService x = new xf.XfjService();
string d = x.getXfj().@return;
XmlDataDocument xd = new XmlDataDocument();
XmlDocument dd = new XmlDocument();
dd.LoadXml(d);
XmlNodeList nodelist = dd.SelectNodes(@"/wsxf/xfjs/xfj");
int i =0; foreach (XmlNode n in nodelist)
{
if (i < 5)
{ string dz = n.Attributes["lj"].Value;
html += "<p class='content'>";
html += "<a target='_blank' href= '" + dz + "'>";
html += "·<span>[网上信访]</span>";
html += (n.ChildNodes[0].InnerText.ToString().Length <= 20 ? n.ChildNodes[0].InnerText.ToString() : n.ChildNodes[0].InnerText.ToString().Substring(0, 20) + "...");
html += "</a></p>";
i++;
}
else
{
break;
} }
return html;