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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With