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

前端 未结 4 776
温柔的废话
温柔的废话 2021-01-02 03:08

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
         


        
4条回答
  •  轮回少年
    2021-01-02 03:44

    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.

提交回复
热议问题