[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode public class User
{
public string? Name { get; set; }
public string? Role { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
// Define a list of users
var users = new List<User>
{
new User { Name = "Alice", Role = "Admin" },
new User { Name = "Bob", Role = "Member" },
new User { Name = "Jay", Role = "Member" },
new User { Name = "Krishna", Role = "Admin" },
new User { Name = "An", Role = "Member" },
new User { Name = "Ka", Role = "Guest" },
};
// CountBy Role using GroupBy and Select
var roleCounts = users
.GroupBy(user => user.Role) // Group users by their roles
.Select(group => new { Role = group.Key, Count = group.Count() }); // Select the role and count for each group
// Print the results
foreach (var roleCount in roleCounts)
{
Console.WriteLine($"Role: {roleCount.Role}, Count: {roleCount.Count}");
}
}
} |