如果可能,将多个条件合并到单个LINQ语句 [英] Consolidate many if conditions to a single LINQ statement if possible
问题描述
我目前正在使用ASP.NET MVC和实体框架代码,首先使用存储库模式显示具有分页的简单用户列表。我添加了通过允许最终用户从两个下拉列表和两个文本框中选择条件的开始和结束日期来过滤该列表的功能。
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.
有更好的这样做比下面的代码,我必须测试所有可能的参数组合,以便编写相应的LINQ查询:
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();
这篇关于如果可能,将多个条件合并到单个LINQ语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!