2

How can I get a total of the count of some columns in a list using LINQ and put this into an object?

I have a list that

List<History> a = getTodayData(); 

where my class History looks like this:

public class History
{
    public Int32 Id { get; set; }
    public string YYMMDD { get; set; }
    public int Quiz { get; set; }
    public int Views { get; set; }
    public int Clicks { get; set; }
    public int Points { get; set; }
}

What I would like is to populate this object with the totals for each of Views, Clicks and Points.

public class Today
{
    public int Views { get; set; }
    public int Clicks { get; set; }
    public int Points { get; set; }
}

Some help / advice would be much appreciated.

Sefe
  • 13,731
  • 5
  • 42
  • 55
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

5

With LINQ you can simply calculate the sums separately:

Today today = new Today {
    Views = a.Sum(history => history.Views),
    Clicks = a.Sum(history => history.Clicks),
    Points = a.Sum(history => history.Points),
}

In the most unlikely event you run into performance issues with this solution, you can always use a non-LINQ foreach loop:

Today today = new Today();
foreach(History history in a) {
    today.Views += history.Views;
    today.Clicks += history.Clicks;
    today.Points += history.Points;
}
Sefe
  • 13,731
  • 5
  • 42
  • 55
  • No, not a typo, this is correct C# and will compile fine. – Sefe Nov 05 '18 at 13:57
  • Sure but.. Ok I have Comma leftover OCD. `var trigger = new [] {1,};` – Drag and Drop Nov 05 '18 at 14:02
  • I routinely put a comma in these cases simply because more often than never, you extend initialization by a few properties later. And adding the comma later is cumbersome. – Sefe Nov 05 '18 at 14:16
1

Use this one and let me know if it is work for you or not.

List<History> a = getTodayData();
 Today t = new Today
           {
            Clicks = a.Sum(h => h.Clicks),
            Views=a.Sum(h=>h.Views),
            Points=a.Sum(h=>h.Points)
        };
Ved_Code_it
  • 704
  • 6
  • 10