我想做一个“GetUsersInRoles”,即我想找到所有MembershipUser在一组角色中至少有一个角色,但我似乎无法理解这个角色.
我有GetUsersInRole,Membership.GetAllUsers(),Linq,……但是怎么样?
任何反馈都非常感谢
汤米
解决方法
这是一个Linq版本,它返回一个MembershipUserCollection,就像类似的Membership方法(FindUsersByEmail,FindUsersByName)一样.它不是很漂亮,因为它依赖于ForEach的副作用:
public static MembershipUserCollection FindUsersByRole(string[] roles) { MembershipUserCollection msc = new MembershipUserCollection(); roles.Select(role => Roles.GetUsersInRole(role)) .Aggregate((a,b) => a.Union(b).ToArray()) .Distinct() .Select( user => Membership.GetUser(user)) .ToList().ForEach( user => msc.Add(user)); return msc; }
或者,如果MembershipUser列表将执行:
public static List<MembershipUser> FindUsersByRole(string[] roles) { var userList = roles.Select(role => Roles.GetUsersInRole(role)) .Aggregate((a,b) => a.Union(b).ToArray()) .Distinct() .Select( user => Membership.GetUser(user)) .ToList(); return userList; }
最后,如果您只需要用户名,则可以跳过一个选择:
public static List<string> FindUsersByRole(string[] roles) { var userList = roles.Select(role => Roles.GetUsersInRole(role)) .Aggregate((a,b) => a.Union(b).ToArray()) .Distinct() .ToList(); return userList; }