user793468
user793468

Reputation: 4976

aggregate and distinct linq query output to list

How can I transform linq query output using aggregate operators and display distinct outputs to a list?

Here is what I have stored in DB, which is being pulled via linq query:

   Date        Hours
07/29/2013      1.3
07/29/2013      2.0
07/30/2013      3.1
07/31/2013      0.1
07/31/2013      5.2
08/01/2013      1.1
08/01/2013      1.1
08/01/2013      2.2
08/02/2013      3.3
08/02/2013      4.0
08/03/2013      2.1

Here is how I want the data:

   Day          Hours
07/29/2013       3.3
07/30/2013       3.1
07/31/2013       5.3
08/01/2013       4.4
08/02/2013       7.3
08/03/2013       2.1

Any help is much appreciated

Upvotes: 1

Views: 548

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

Use GroupBy and Sum:

var result = db.Table
    .GroupBy(r => r.Date)
    .Select(g => new{ Day=g.Key, Hours=g.Sum(r=> r.Hours) })

If Date is actually a DateTime you should use r.Date.Date to remove the time portion.

Upvotes: 7

Related Questions