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;
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With