Search code examples
c#asp.net-mvcasp.net-identity

How do I get the List of Role and Number of users in them asp.net mvc


Please how do I get the list of roles, along with the number of users having the role? something like this enter image description here

I have tried this

var users = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("User")).count;

but this is just for one role. I need it for all the roles, and when a new role is added in the db, it should also add to the list.

Thanks


Solution

  • Following code will be helpful to you.

    var  result = ( from r in userManager.UserRoles 
                    join u in userManager.Users on r.UserId equals u.Id
                    group  new { r, u } by new { r.RoleId } into grp
                    select new { name = grp.FirstOrDefault().r.Name, count=grp.Count()}).ToList();