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

查看:147
本文介绍了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. Similary, 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类型,可以添加 Where 子句,并在结尾生成结果:

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天全站免登陆