I often find myself doing the following index-counter messiness in a foreach loop to find out if I am on the first element or not. Is there a more elegant way to do this in C#, something along the lines of if(this.foreach.Pass == 1) etc.?
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++;
}
Another approach is to accept that the “ugly part” has to be implemented somewhere and provide an abstraction that hides the “ugly part” so that you don’t have to repeat it in multiple places and can focus on the specific algorithm. This can be done using C# lambda expressions (or using C# 2.0 anonymous delegates if you’re restricted to .NET 2.0):
Now you can use this reusable method to implement your algorithm like this:
You could design the abstraction differently depending on the exact repeating pattern. The good thing is that – thanks to lambda expression – the structure of the abstraction is completely up to you.