Linq - multiple rows as string

2019-08-24 17:46发布

问题:

Lets assume that I have Table which contains Username and the other one which contains FirstName. A single user can have multiple FirstNames:

How can I obtain a record which will contain Username and all first names separated by comma?

i. e.

Users
id | Username
1 | Test

Names
UserId | FirstName
1 | Mike
1 | John

I would like to receive a record which will contain

Test, "Mike, John"

How can I do that?

Edit: What if Users table will have more columns which I want to get?

i. e.

id | Username | Status
1  | Test     | Active

How to get Test, Active, "Mike, John"?

回答1:

You can use GroupBy and String.Join

var userGroups = from u in users
     join n in names
     on u.ID equals n.UserID
     group new{n, u} by n.UserID into UserGrp
     select new
     {
         Username = UserGrp.Key,
         Status = UserGrp.First().u.Status,
         Names = string.Join(",", UserGrp.Select(x => x.n.Name))
     };

foreach (var ug in userGroups)
   Console.WriteLine("{0}, {1}, \"{2}\"", ug.Username, ug.Status, ug.Names);