realPro
realPro

Reputation: 1846

How to Group and Sum List of Lists using Linq

I have a List of Lists that holds an hourly object. I need to group all the lists into one, by grouping on the hour and summing the clicks and blocks. I wrote the code using a for loop, but wonder how can I do it using a Linq.

    class hourly
    {
        public int clicks { get; set; }
        public int blocks { get; set; }
        public int hour { get; set; }

    }


       var m = new List<List<hourly>>();

     
     /// populate m from DB

   
        var n = new List<hourly>(24);

        for (int i = 0; i < 24; i++)
        {
            n.Add(new hourly());
            n[i] = new hourly() { hour = i, clicks = m.Sum(x => x[i].clicks), blocks = m.Sum(x => x[i].blocks) };
        }

Upvotes: 1

Views: 459

Answers (1)

Guru Stron
Guru Stron

Reputation: 141845

I suppose you are looking for SelectMany and GroupBy:

var result = m
    .SelectMany(ll => ll)
    .GroupBy(h => h.hour)
    .Select(g => new hourly
    {
        hour = g.Key,
        blocks = g.Sum(h => h.blocks),
        clicks = g.Sum(h => h.clicks)
    })
    .ToList();

If there are no instances of hourly in your db for some concrete hour and you need to have all in the final result you can add dummy ones after SelectMany, for example:

.Concat(Enumerable.Range(0, 24).Select(i => new hourly {hour = i}))

If ordering is important apply OrderBy before ToList.

Upvotes: 4

Related Questions