Search code examples
asp.net-mvcstringvb.netstring-concatenation

How to remove the trailing comma & space in a for-each loop that generates links in a mvc vbhtml view?


Given a loop like:

  @For Each x In item.PostCategory
          Dim cats = x.CategoryName & ", "
          @Html.ActionLink(cats, 
         "PostsByCategory", "Posts", New With {.Category = x.CategoryName.ToSeoUrl, 
         .Page = Nothing}, Nothing) 
      Next

I need to remove only the last comma and space - everything I have tried removes the commas and spaces in the middle as well as the end. The loop renders categories and I want them separated by a comma and space but do not need or want the trailing comma and space. Each category needs to be a separate link so string.join won't work. I tried trim.substring - that removes the commas in the middle. TrimEnd did not work. I have searched and have not found a solution.

Instead of World, Science, - i want World, Science


Solution

  • You can try to check if x is the last item in PostCategory. If it is true, then append an empty string, else append comma and space :

    Dim cats = x.CategoryName  & IIf(x.Equals(item.PostCategory.Last()), "", ", ")