【发布时间】:2010-02-21 23:39:11
【问题描述】:
我经常发现自己在 foreach 循环中执行以下 index-counter messiness 以确定我是否在 第一个元素 上。在 C# 中是否有一种更优雅的方式来做到这一点,类似于 if(this.foreach.Pass == 1) 等?
int index = 0;
foreach (var websitePage in websitePages) {
if(index == 0)
classAttributePart = " class=\"first\"";
sb.AppendLine(String.Format("<li" + classAttributePart + ">" +
"<a href=\"{0}\">{1}</a></li>",
websitePage.GetFileName(), websitePage.Title));
index++;
}
【问题讨论】:
-
我认为老实说方法很好,很简单等。你看过火花视图引擎吗?只是猜测你在做什么...... PK :-)
-
只是一个快速的想法......你可以单独处理第一个案例,然后在循环中处理其余的案例吗? (在 do while 循环中的相同想法)
-
@Paul 是的 scott hanselman 在 spark 视图引擎上的播客很好,感谢提醒,将重访:hanselminutes.com/default.aspx?showID=210
-
与其在你的第一个
li中添加一个类,为什么不在你的 CSS 中使用li:first-child呢?