Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consolidate many if conditions to a single LINQ statement if possible

I am currently using ASP.NET MVC and Entity Framework Code First using the repository pattern to display a simple list of users that has paging. I am adding the ability to filter that list by allowing the end user to select conditions from two drop downs and two text boxes with start and end date.

Is there a better way to do this than the code below where I have to test for all possible combinations of parameters in order to write the appropriate LINQ query:

public IEnumerable<User> GetAllByCondition(int? condition1, int? condition2, DateTime? startDate, DateTime? endDate)
{
    if (condition1.HasValue && startDate.HasValue && endDate.HasValue)
    {
        return Database.Set<User>().Where(x => x.Condition1 == condition1.Value && x.Date > startDate.Value && x.Date <= endDate.Value).ToList();
    }

    if (condition1.HasValue && condition2.HasValue)
    {
        return Database.Set<User>().Where(x => x.Condition1 == condition1.Value && x.Condition2 == condition2.Value).ToList();
    }

    if (condition1.HasValue)
    {
        return Database.Set<User>().Where(x => x.Condition1 == condition1.Value).ToList();
    }

    .... and the list goes on
}

This can quickly get bloated if I add one one more condition in the future.

like image 649
Thomas Avatar asked Dec 13 '22 07:12

Thomas


1 Answers

Use the fact that queries compose - you can just keep calling Where to add more conditions:

var query = Database.Set<User>();

if (condition1.HasValue)
{
    query = query.Where(x => x.Condition1 == condition1.Value);
}
if (condition2.HasValue)
{
    query = query.Where(x => x.Condition2 == condition2.Value);
}
...
return query.ToList();
like image 74
Jon Skeet Avatar answered Mar 15 '23 23:03

Jon Skeet