Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please how do I get the list of roles, along with the number of users having the role? something like Admin 3, Staff 7, Supervisor 12 etc.

What I have tried:

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
Posted
Updated 16-Jan-18 19:54pm

You'll get an idea how to implement.

Assigning Roles to Users (C#) | Microsoft Docs[^]
 
Share this answer
 
Comments
Ifeanyi Wisdom Onyejekwe 17-Jan-18 2:25am    
Well, it just made it complicated...Thanks anyway
Hello,
Try something like this way
DataTable dtuserrole=new DataTable();
dtuserrole.Columns.Add("Name");
dtuserrole.Columns.Add("Role");

dtuserrole.Rows.Add("A","Admin");
dtuserrole.Rows.Add("B","Admin");
dtuserrole.Rows.Add("C","User");
dtuserrole.Rows.Add("D","User");
dtuserrole.Rows.Add("E","Stuff");
dtuserrole.Rows.Add("F","User");
dtuserrole.Rows.Add("G","Superuser");
dtuserrole.Rows.Add("H","User");
dtuserrole.AcceptChanges();

var results = (from p in dtuserrole.AsEnumerable()
               group p by new {Role=p.Field<string>("Role")}into g
      select new { Role = g.Key, Count = g.Count()});

and the output will be
		foreach(var dr in results)
				Console.WriteLine("Role: "+dr.Role + "; Count: "+dr.Count);

Role: { Role = Admin }; Count: 2
Role: { Role = User }; Count: 4
Role: { Role = Stuff }; Count: 1
Role: { Role = Superuser }; Count: 1

Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900