I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

Trying to create grouped records with linq

I have records like this in 1 list :

Id     Title     Name      Basic     Message
10     Stats2    abc       10         sldjs
10     Stats2    pqr       20         sldjs
10     Stats2    xyz       30         sldjs
10     Stats2    abc       40         sldjs


11     Stats3    aaa       0         sldjs
11     Stats3    bbb       0         sldjs
11     Stats3    ccc       0         sldjs
11     Stats3    ddd       0         sldjs

I have a variable of type List of class which hold below records:

var list = new List<Stats>();//this variable hold all above records.

Now I am trying to create records like below from list variable :

[0]:Stats2:
        abc         
            10  sldjs
            40  sldjs
        pqr
            20  sldjs
        xyz
            30  sldjs

[1]:Stats3:
        aaa         
            0  sldjs
        bbb
            0  sldjs
        ccc
            0  sldjs
        ddd 
            0  sldjs

This is how I am trying but not getting how to create inner nested children like (2 abc records shown above):

var data =list.GroupBy(ed =>ed.Id)
               .Select
               (

               )

Upvotes: 1

Views: 54

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

You need to group the inner records as well. The result could be something like a Dictionary<int, Dictionary<string, List<Stats>>>. The keys of the outer dictionary would be the ID values and the inner keys the Name values and the values would be lists of the Stats having that Title and Name:

var result = list.GroupBy(rec => rec.ID)
                 .ToDictionary(
                     group => group.Key,
                     group => group.GroupBy(stat => stat.Name)
                                   .ToDictionary(g => g.Key, g => g.ToList())
                              );

You can access the values in the result like that:

result[10]["abc"]

The above example would be a list containing the Stats with Basic10 and 40.


If you only want to keep Basic and Message in the final records, you can use Select to project the Stats to an anonymous type:

var result = list.GroupBy(rec => rec.ID)
                 .ToDictionary(
                     group => group.Key,
                     group => group.GroupBy(stat => stat.Name)
                                   .ToDictionary(g => g.Key, g => g.Select(stat => new {stat.Title, stat.Basic, stat.Message}).ToList())
                              );

Upvotes: 2

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

var data =list.GroupBy(p => p.Title).Select(p => new
            {
                Title = p.Key,
                Items = p.GroupBy(q => q.Name)
                         .ToDictionary(q => q, q => new { q.Basic, q.Message })
            });

Upvotes: 2

Related Questions