Looping through a list in razor and adding a separator between items

asp.net-mvc, razor

Solution

You can use `string.Join`:

@Html.Raw(string.Join("|", model.Items.Select(s => string.Format("<span>{0}</span>", s.Name))))

Using `string.Join` negates the need to check for the last item.

You can mix this with a Razor `@helper` method for more complex markup:

@helper ComplexMarkup(ItemType item)
{ 
    <span>@item.Name</span>
}

@Html.Raw(string.Join("|", model.Items.Select(s => ComplexMarkup(s))))

You could even create a helper method to abstract the `Html.Raw()` and `string.Join()` calls:

public static HtmlString LoopWithSeparator
    (this HtmlHelper helper, string separator, IEnumerable<object> items)
{
    return new HtmlString
          (helper.Raw(string.Join(separator, items)).ToHtmlString());
}

Usage:

@Html.LoopWithSeparator("|",  model.Items.Select(s => ComplexMarkup(s)))

Problem

I have a list of items which I want to output in a razor view. Between each item I want to add a separator line, like this: ``` item1 | item2 | item3 ``` The simplest way to loop through items is with a foreach: ``` @foreach(var item in Model.items){ <span>@item.Name</span> | } ``` Unfortunately this adds an extra separator line at the end of the list. Is there a simple way to skip this last separator line?

Original source