Linq:有条件地向where子句添加条件 [英] Linq: adding conditions to the where clause conditionally

查看:42
本文介绍了Linq:有条件地向where子句添加条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的查询

(from u in DataContext.Users
       where u.Division == strUserDiv 
       && u.Age > 18
       && u.Height > strHeightinFeet  
       select new DTO_UserMaster
       {
         Prop1 = u.Name,
       }).ToList();

我想根据是否向运行此查询的方法提供了年龄、身高等各种条件来添加这些条件.所有条件将包括用户部门.如果提供了年龄,我想将其添加到查询中.同样,如果提供了高度,我也想添加它.

I want to add the various conditions like age, height based on whether those conditions were provided to the method running this query. All conditions will include user Division. If age was supplied I want to add that to the query. Similarly, if height was provided I want to add that as well.

如果这是使用 sql 查询完成的,我会使用字符串生成器将它们附加到主 strSQL 查询.但是在 Linq 中,我只能想到使用 IF 条件,我将编写三次相同的查询,每个 IF 块都有一个附加条件.有没有更好的方法来做到这一点?

If this were to be done using sql queries I would have used string builder to have them appended to the main strSQL query. But here in Linq I can only think of using an IF condition where I will write the same query thrice, with each IF block having an additional condition. Is there a better way to do this?

推荐答案

如果不调用 ToList() 和你最终映射到 DTO 类型,你可以添加 Wherecode> 子句,并在最后构建结果:

If you do not call ToList() and your final mapping to the DTO type, you can add Where clauses as you go, and build the results at the end:

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();

这仍然只会导致对数据库的单次调用,这将与一次性编写查询一样有效.

This will still only result in a single call to the database, which will be effectively just as efficient as writing the query in one pass.

这篇关于Linq:有条件地向where子句添加条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆