How do you add dynamic 'where' clauses to a linq query?

后端 未结 6 1065
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 07:19

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          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 08:01

    Here's one way of adding a variable number of where clauses to your LINQ query. Note that I haven't touched your bitmask logic, I just focused on the multiple wheres.

    // C#
    private List GetUsersFromRoles(uint[] UserRoles)
    {
       var users = dc.Users;
    
       foreach (uint role in UserRoles)
       {
          users = users.Where(u => (u.UserRolesBitmask & role) == role);
       }
    
       return users.ToList();
    }
    

    EDIT: Actually, this will AND the where clauses and you wanted to OR them. The following approach (a inner join) works in LINQ to Objects but can not be translated to SQL with LINQ to SQL:

    var result = from user in Users
                 from role in UserRoles
                 where (user.UserRolesBitmask & role) == role
                 select user;
    

提交回复
热议问题