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
Combining the other answers here with this article on inline templates, I came up with this helper method, which can be put in an extension class:
public static HelperResult Join(this IEnumerable list, Func template, Func separator)
{
var first = true;
var result = new HelperResult(writer =>
{
foreach (var item in list)
{
if (first == false)
separator(item).WriteTo(writer);
first = false;
template(item).WriteTo(writer);
}
});
return result;
}
The way to use it would then be
@Model.ListOfItems.Join(
@
@item.Name
,
@ | )
This supports html in both the items and the separator.