0

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());
2
  • Is this correct Does it work? Commented Jun 11, 2020 at 3:30
  • @mjwills, yes it does. Commented Jun 11, 2020 at 3:50

1 Answer 1

1

Why not simply

string.Join("|", 
    company.Users.Select(u => string.Join(",", 
        u.Roles.Select(r => r.RoleName)))
)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Don't know why I went the complicated way instead of such a simple solution. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.