I have a schema like below:
public class Company
{
public string Name { get; set; }
public List<User> Users { get; set; }
}
public class User
{
public string UserName { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public string RoleName { get; set; }
//other properties
}
Now I want to build a string which contains comma-separated roles and separated by pipe for each user.
For example, if a sample JSON for this object is as below:
{
"Name" : "Comp1",
"Users" : [{
"UserName" : "User1",
"Roles" : [{
"RoleName" : "Guest"
},
{
"RoleName" : "OpUser"
}]
},
{
"UserName" : "User2",
"Roles" : [{
"RoleName" : "Manager"
},
{
"RoleName" : "Principal"
}]
}]
}
The expected output is
Guest,OpUser|Manager,Principal
I wrote below LINQ code to do this. It works but I believe it can be simplified. Is this correct or can it be simplified more?
var userList = string.Join("|", company.Users.
SelectMany(c => c.Roles.Select(d => new { user = c.UserName, role = d.RoleName }))
.GroupBy(g => g.user, (key, g) => new { UserName = key, Roles = string.Join(",", g.Select(r=>r.role))})
.Select(i=>i.Roles).ToList());
Is this correctDoes it work?