How to add string.join to foreach loop

Viewed 368

I show the categories of my i'th product on the View, but I want to add a link and put commas between them.

@for (int i = 0; i < Products.Count(); i++)
{
    <tr>
        <td>
            <span> @Model.Products[i].ProductName </span>
            @foreach (var item in Model.Products[i].ProductCategories)
            {
                <a href="/home/@item.ItemName"> @item.ItemName, </a>
            }
        </td>
   </tr>

It looks like this => Computer, Technology, Desktop,

I want this => Computer, Technology, Desktop

I don't want a comma in the last item

I can show it this way but I can't add <a href=""></a>

 <span>@string.Join(", ", Model.Products[i].ProductCategories.Select(p => p.Category.CategoryName))</span>
3 Answers

I think you can use LINQ instead of foreach:

@for (int i = 0; i < Products.Count(); i++)
{
    <tr>
        <td>
            <span> @Model.Products[i].ProductName </span>
            @Html.Raw(String.Join(", ", Model.Products[i].ProductCategories.Select(category => $@"<a href=""/home/{Html.Encode(category.CategoryName)}"">{Html.Encode(category.CategoryName)}</a>")))
        </td>
   </tr>

But I won't say this is the most Razor way to do it. You should probably be using something like Html.ActionLink at this point instead of manually putting in the a tag.

Using a brute force approach…

Have you considered using a for loop instead of a foreach loop? Inside the for loop, if the loop index j is less than the collection count – 1, then add the comma.

Example, using your code structure…

@for (int j = 0; j < Model.Products[i].ProductCategories.Count(); j++) 
{
    If (j < Model.Products[i].ProductCategories.Count() – 1)
    {
        <a href="/home/@item.ItemName"> Model.Products[i].ProductCategories[j].ItemName, </a>
     }
     else
     {
         <a href="/home/@item.ItemName"> Model.Products[i].ProductCategories[j].ItemName</a>
     }
}

Perhaps you could do something like this. Could not test it, but should capture the gist.

<span>
    @string.Join(
        ", </a>", 
        Model.Products[i]
            .ProductCategories
            .Select(
                p => "<a href=\"" + p.Category.CategoryName + "\""))
    </a>
</span>
Related