Search code examples
c#loopsrazorforeach

Razor - First Element of ForEach or ForEach Loop only once


I would like this ForEach to return h3 to me only once, instead of three which is the length of the array. How can I do? Thanks to those who will answer

 @foreach (var winelistObj in Model.winetype.Where(s => s.name == Request.Query["wine"]))
{
 <h3 class="text-uppercase font-logo text-regular letter-spacing-200">@winelistObj.name</h3>
}

Solution

  • Maybe you want to concat all matching wines comma separated, then use string.Join:

    @{ string matchingWines = string.Join(",", Model.winetype.Where(s => s.name == Request.Query["wine"]).Select(w=> w.name)); }
    <h3 class="text-uppercase font-logo text-regular letter-spacing-200">@matchingWines</h3>
    

    You could add an if(!string.IsNullOrEmpty(matchingWines)) { ... } so that you don't render the h3 if there was no matching wine or render a different message.