Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ to group by a list of objects in the format as shown below [duplicate]

Tags:

c#

linq

group-by

I have a list of data in this format -

User    Role        Code
John    admin       101
John    admin       101
John    admin       100
Smith   superadmin  150
Smith   superadmin  120
Smith   superadmin  130
Smith   superadmin  140
Smith   superadmin  160
John    review      180
John    review      190
John    review      200

I would like to collapse this based on the common user like this -

 User    Role        Code
 John    admin       100,101
 Smith   superadmin  120,130,140,150,160     
 John    review      180,190,200

I've tried this -

result = userRoles.GroupBy(l => l.User).Select(u => new UserRole()
{ 
    Code = string.Join(", ", userRoles.Where(d => d.User ==  u.Key)
                                      .Select(d => d.Code)
                                      .ToArray()),
    User = u.Key,
}).ToList();

I got it to a point where I am able to show user and code in the format with the above code , just trying to figure how to fit in the Role , any help would be greatly appreciated.


var userRoles = new[]
{
    new UserRole() { User = "John", Role = "admin", Code = "101" },
    new UserRole() { User = "John", Role = "admin", Code = "101" },
    new UserRole() { User = "John", Role = "admin", Code = "100" },
    new UserRole() { User = "Smith", Role = "superadmin", Code = "150" },
    new UserRole() { User = "Smith", Role = "superadmin", Code = "120" },
    new UserRole() { User = "Smith", Role = "superadmin", Code = "130" },
    new UserRole() { User = "Smith", Role = "superadmin", Code = "140" },
    new UserRole() { User = "Smith", Role = "superadmin", Code = "160" },
    new UserRole() { User = "John", Role = "review", Code = "180" },
    new UserRole() { User = "John", Role = "review", Code = "190" },
    new UserRole() { User = "John", Role = "review", Code = "200" },
};

public class UserRole
{
    public string User;
    public string Role;
    public string Code;
}
like image 356
learner999 Avatar asked Jan 01 '23 06:01

learner999


1 Answers

You can group by both user and role by creating an anonymous type. Something like this:

result = userRoles.GroupBy(l => new { l.User, l.Role }).Select(u => new
{
    Code = string.Join(", ", u.Select(d => d.Code).Distinct().OrderBy(d => d)),
    User = u.Key.User,
    Role = u.Key.Role
}).ToList();
like image 99
Matt Burland Avatar answered Jan 02 '23 20:01

Matt Burland