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

后端 未结 6 1070
伪装坚强ぢ
伪装坚强ぢ 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:05

    Assuming your UserRoles values are themselves bitmasks, would something like this work?

    private List GetUsersFromRoles(uint[] UserRoles) {
        uint roleMask = 0;
        for (var i = 0; i < UserRoles.Length;i++) roleMask= roleMask| UserRoles[i];
        // roleMasknow contains the OR'ed bitfields of the roles we're looking for
    
        return (from u in dc.Users where (u.UserRolesBitmask & roleMask) > 0) select u);
    }
    

    There's probably a nice LINQ syntax that'll work in place of the loops, but the concept should be the same.

提交回复
热议问题