How to apply Where Clause condition in foreach loop in MVC razor view?

Total Post:4

Points:28
C#
 467  View(s)
Ratings:
Rate this:

Hi,

Below is my code,

 @foreach (var item in Model)

                        {
                            if (item.Type == "Technical") {
  <a style="margin-bottom:30px" class="text-white contentFontSize" href="@Url.Action("Index", "Question", new { FilterBy = "technology", FilterText = item.Technology, Type = "Technical" })">
                                 <span class="float-left col-md-2" style="padding: 20px; text-transform: uppercase">@item.Technology &nbsp;&nbsp; @item.TotalCount </span>
                            </a>
   }
                        }

I want to write my conditional statement in foreach loop. It is possible to write a conditional statement with foreach loop. If yes please give me some idea.

  1. Post:44

    Points:310
    Re: How to apply Where Clause condition in foreach loop in MVC razor view?

    Hi Shaan,

    Of course, you can write your conditional statement within foreach loop using where clause. Please follow the line of code.

     @foreach (var item in Model.Where(x => x.Type == "Technical"))
    
                            {
                                <a style="margin-bottom:30px" class="text-white contentFontSize" href="@Url.Action("Index", "Question", new { FilterBy = "technology", FilterText = item.Technology, Type = "Technical" })">
                                    <span class="float-left col-md-2" style="padding: 20px; text-transform: uppercase">@item.Technology &nbsp;&nbsp; @item.TotalCount </span>
                                </a>
                            }

    I hope its informative...

Answer