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

前端 未结 4 791
温柔的废话
温柔的废话 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:55

    Not sure if this is the simplest way, or if these is a more elegant way, but you could do something like;

    @foreach ( var item in Model.items){
        @item.Name @(Model.items[Model.items.Count - 1] != item ? "|" : "")
    }
    

    So you are basically checking to see if the item is the last item in the list.

    Not tried this code sample, so you might need to tweek it.

提交回复
热议问题