asp.net c# membership: how to do a GetUsersInRoles (multiple roles)H

tommyp picture tommyp · Jan 2, 2011 · Viewed 8.2k times · Source

I want do a "GetUsersInRoles", i.e. I want to find all MembershipUser's having at least one of the roles in a set of roles, but I can't seem to get my head around this one.

I've got GetUsersInRole, Membership.GetAllUsers(), Linq,... but how?

Any feedback is greatly appreciated

Tommy

Answer

BrokenGlass picture BrokenGlass · Jan 3, 2011

Here's a Linq version, it returns a MembershipUserCollection just like the similar Membership methods (FindUsersByEmail, FindUsersByName). It's not very pretty since it relies on the ForEach side effect:

    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;
    }

Alternatively if a list of MembershipUser will do:

    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;
    }  

And finally if you just need the user names you can skip one select:

    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;
    }