Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
                   });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading