Find all User that are NOT in a specifv Role using: Roles.GetUsersInRole or different

669 views Asked by At

I need populate an array with a list of Users that ARE NOT PRESENT in a specific Role and COUNT the result.

At the moment I use this code, but I am not able to get the Users outside "CMS-ADMINISTRATOR " role.

Any idea how to do it and better write the Count section?

       string[] usersInRole;
       usersInRole = Roles.GetUsersInRole("CMS-ADMINISTRATOR");
       int c = usersInRole.Count();
4

There are 4 answers

0
Øyvind Bråthen On

Not sure about getting users outside the "CMS-ADMINISTRATOR" role, but at least you can write the original code better like this:

 int count = Roles.GetUsersInRole("CMS-ADMINISTRATOR").Count();
2
Andy Mikula On

If you just need the number of users not in the role, you can subtract the number of users in the role from the total number of users:

int count = Membership.GetAllUsers.Count - Roles.GetUsersInRole("CMS-ADMINISTRATOR").Count();
3
Carles Company On

Maybe this:

var users=Membership.GetAllUsers().Cast<MembershipUser>()
           .Count(t=>!Roles.IsUserInRole(t.UserName,"CMS-ADMINISTRATOR"));

Or use what Andy Mikula suggests which is simpler if you just need the count.

0
Don Thomas Boyle On

Please try,

            var usernames = Roles.GetUsersInRole("Administrator");
            var adminUsers = db.UserProfiles
                 .Where(x => !usernames.Contains(x.UserName)).ToList();

adminusers.count

you can also return it to the view

return View(adminUsers);