Jeremy
Jeremy

Reputation: 147

Get list of list of objects from linq query

Is there any way to query a list of objects, group them and then output them as their own list as a list of lists? I don't know how to explain it so I'll show you.

public class Note
{
    string CreatorID;
    string Title;
    string Text;
}

I have a populated list of notes (List<Note> noteList). There are multiple creators and multiple notes for each creator. I'm trying to figure out if there's a way using a LINQ query to group the notes by CreatorID then, separate them and output them as a list of list of notes (List<List<Note>> creatorsNotes). This way I can loop through creatorsNotes to get creators and their list of notes.

Upvotes: 0

Views: 143

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Sure, let's let list be the List<Note>:

var creatorNotes = list
    .GroupBy(note => note.CreatorID)
    .Select(g => new
    {
        g.CreatorID,
        Notes = g.ToList()
    })
    .ToList();

As pointed out by Reed, this is a list of an anonymous type that indicates the grouped CreatorID at the root as well as the Notes associated with that CreatorID.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

The easiest would be to use ToLookup:

var groups = noteList.ToLookup(n => n.CreatorID);

foreach(var group in groups)
{
    Console.WriteLine("Items with CreatorID {0}", group.Key);
    foreach(var item in group)
          Console.WriteLine("   Title: {0}", item.Title);
}

You could also use GroupBy if needed. Note that these will not directly create a List<List<Note>>, however. If that is required, you could do:

List<List<Note>> grouped = noteList.GroupBy(n => n.CreatorID)
                                   .Select(g => g.ToList()) 
                                   .ToList();

Upvotes: 6

Related Questions