To convert if condition to linq in cshtml

Code

if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
    //can display those records..
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
    if(Model.Date <= 30 days)
    {
        //can display those records..
    }
}

I have tried the following code and unable to complete it fully as expected

 @Html.Partial("Filter", new IndexModel() 
            { 
                Id = Model.Id, 
                Collection = Model.Collection.Where((a => a.CurrentStatus == 1 || a.CurrentStatus == 2)
                                                && ) 
            })

How to convert the above if condition to linq in cshtml. Thanks

>Solution :

the else-if relationship is an OR relationship. So simply combine the two lines. the inner nested if inside the else if is an AND relationship. This would go into the second set of parentheses

Collection = Model.Collection.Where
       (
          (a => a.CurrentStatus == 1 || a.CurrentStatus == 2) ||
          ((a.CurrentStatus == 3 || a.CurrentStatus == 4) && a.Date != null  && a.Date <= 30) 
       ) 

EDIT:

Here is another suggestion: extract the readable code into an own method that evaluates the condition and returns the boolean result. This way you can make a predicate that can be accepted by the Where method:

private bool IsForDisplay( ModelDataType Model )
{
    if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
    {
        //can display those records..
        return true;
    }
    else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
    {
        if(Model.Date <= 30 days)
        {
            //can display those records..
            return true;
        }
    }
    return false;
}

now you can use it simply in the linq expression:

 @Html.Partial("Filter", new IndexModel() 
                  { 
                       Id = Model.Id, 
                       Collection = Model.Collection.Where(a => IsForDisplay(a))
                   });

Leave a Reply