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

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


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


谢谢你的时间..


慕田峪4524236
浏览 1022回答 3
3回答

慕仙森

我通常使用方法链接,但有同样的问题。这是我使用的扩展public static IQueryable<T> ConditionalWhere<T>(&nbsp; &nbsp; &nbsp; &nbsp; this IQueryable<T> source,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Func<bool> condition,&nbsp; &nbsp; &nbsp; &nbsp; Expression<Func<T, bool>> predicate)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (condition())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return source.Where(predicate);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return source;&nbsp; &nbsp; }它有助于避免链断裂。也同样ConditionalOrderBy和ConditionalOrderByDescending是有益的。
打开App,查看更多内容
随时随地看视频慕课网APP