How to use LINQ to select into an object?

Abe Miessler picture Abe Miessler · Jul 19, 2012 · Viewed 99k times · Source

I have data that looks like so:

UserId   |  SongId
--------   --------
1          1
1          4
1          12
2          95

I also have the following class:

class SongsForUser
{
    public int User;
    public List<int> Songs;
}

What I would like to do is use LINQ to select from my data to create a collection of SongsForUser objects. Below is what I have come up with so far:

var userCombos = songs.UserSongs.Select(x => new SongsForUser() { User = x.UserId, 
                                                                  Songs = /*What goes here?*/ });

How would I go about populating my Songs List?

So the result should be two SongsForUser objects. For user 1 it would have 3 items in the Songs list. For user 2 it would have 1 item in the Songs list.

Answer

ForEveR picture ForEveR · Jul 19, 2012
songs.UserSongs.GroupBy(x => x.User).Select(g => new SongsForUser() 
{ 
    User = g.Key,
    Songs = g.Select(s => s.SongId).ToList()
});