我有一个这样的查询
(from u in DataContext.Users
where u.Division == strUserDiv
&& u.Age > 18
&& u.Height > strHeightinFeet
select new DTO_UserMaster
{
Prop1 = u.Name,
}).ToList();
我想根据是否向运行此查询的方法提供这些条件来添加年龄、高度等各种条件。所有条件都将包括用户划分。如果提供了年龄,我想将其添加到查询中。同样,如果提供了高度,我也想添加它。
如果这是使用 sql 查询来完成的,我会使用字符串生成器将它们附加到主 strSQL 查询中。但在 Linq 中,我只能想到使用 IF 条件,其中我将编写相同的查询三次,每个 IF block 都有一个附加条件。有更好的方法吗?
最佳答案
如果您不调用 ToList()
以及最终映射到 DTO 类型,则可以随时添加 Where
子句,并在最后构建结果:
var query = from u in DataContext.Users
where u.Division == strUserDiv
&& u.Age > 18
&& u.Height > strHeightinFeet
select u;
if (useAge)
query = query.Where(u => u.Age > age);
if (useHeight)
query = query.Where(u => u.Height > strHeightinFeet);
// Build the results at the end
var results = query.Select(u => new DTO_UserMaster
{
Prop1 = u.Name,
}).ToList();
这仍然只会导致对数据库的一次调用,这实际上与一次性编写查询一样高效。
关于Linq:有条件地向 where 子句添加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10884651/