Search code examples
asp.net-corerazor

ASP.NET Core : how can I replace a character at int values in foreach or for loop?


I have a loop whose values ​​are int. The values ​​are displayed in this way: 14 16 18.

I want to place a dash - between the numbers of the characters: 14-16-18

I searched a lot and did not find a suitable solution :(

Loop:

foreach (int size in SizeList)
{
    <span class="size">@size </span>
}

Solution

  • You may also be able to handle the task with the Join() method of the string class

    <span>class="size">@(string.Join("-", sizeList.Select(i => i.ToString())))</span>
    

    or, possibly using a more defensive style of coding if you are in danger of null reference exceptions here:

    @if(sizeList is not null)
    {
        <span>class="size">@(string.Join("-", sizeList.Select(i => i.ToString())))</span>
    }
    

    Actually, the explicit conversion to string is not necessary as in the answer given by @Dave Bry so you can get by with less code too:

    <span>class="size">@string.Join("-", sizeList)</span>