如何在linq查询中添加动态“where”子句? [英] How do you add dynamic 'where' clauses to a linq query?

查看:146
本文介绍了如何在linq查询中添加动态“where”子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含用户角色的位掩码的用户表。下面的linq查询返回角色包括1,4或16的所有用户。

  var users = from d in dc.Users 
其中((u.UserRolesBitmask& 1)== 1)
|| ((u.UserRolesBitmask& 4)== 4)
|| ((u.UserRolesBitmask& 16)== 16)
select u;

我想将其重写为以下方法,从给定角色返回所有用户我可以重用它:

 私人列表<用户> GetUsersFromRoles(uint [] UserRoles){} 

有关如何动态构建查询的任何指针?谢谢

解决方案

您可以使用 PredicateBuilder 类。



PredicateBuilder已在 LINQKit NuGet软件包


LINQKit是一套免费的扩展LINQ to SQL和实体框架的高级用户。



I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16.

var users = from u in dc.Users
            where ((u.UserRolesBitmask & 1) == 1)
               || ((u.UserRolesBitmask & 4) == 4)
               || ((u.UserRolesBitmask & 16) == 16)
            select u;

I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:

private List<User> GetUsersFromRoles(uint[] UserRoles) {}

Any pointers on how to dynamically build my query? Thanks

解决方案

You can use the PredicateBuilder class.

PredicateBuilder has been released in the LINQKit NuGet package

LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.

这篇关于如何在linq查询中添加动态“where”子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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