Ben McCallum's Blog

Dissecting ASP.NET MVC3, CSS3, HTML5, jQuery and a whole lot of other things ending with numbers…

Archive for the tag “C#”

a foreach loop with an index thanks to LINQ

I’ve been spending a lot of time using ASP.NET MVC3 and the new Razor syntax. One of the newer things for me is to throw away the from the days of WebForms and throw the foreach loop straight into View template markup. Recently I needed to maintain an index of the current item when iterating through my Model so that I could add a class in the markup to every third item in the IEnumerable.

Sure, you could use a simple for loop like so:

@model IEnumerable

<ul>
for (int i=1; i<=Model.Count(); i++)
{
<li @if (i%3 == 0) { <text>class=”last” </text>}>
Movie Name: @Model.ElementAt(i).Title
<li>
}
</ul>

But the markup isn’t as readable and it isn’t completely clear that you are iterating over the Model elements until you look within the for loop. You are throwing away all of the advantages of the foreach syntax simply to gain the index of the element. Surely there’s is a better way you ask? Luckily there is thanks to the power of LINQ:


@model IEnumerable

<ul>
@foreach (var movie in Model.Select((x, i) => new { Data = x, Index = i }))
{
<li @if ((movie.Index + 1) % 3 == 0) { <text>class=”last” </text>}>
Movie Name: @movie.Data.title
</li>
}
</ul>

Now you can access the index via movie.Index and the strongly-typed Movie object via movie.Data. Plus the code is much more readable and consistent with the more commonly used foreach syntax.

Happy coding 🙂

Post Navigation