calculate the total time grouping by date and id using linq

My data looks like this

ID  |   START_DATE          |   END_DATE                |   Chapter
1       01/03/2013 05:15:14     01/03/2013 06:20:14         1
1       01/03/2013 06:25:33     01/03/2013 06:40:11         2
2       01/03/2013 05:01:34     01/03/2013 05:30:13         1
2       01/03/2013 05:31:20     01/03/2013 06:30:13         2
2       01/03/2013 06:32:20     01/03/2013 07:20:01         3
1       02/03/2013 05:15:14     01/03/2013 06:20:14         1
1       02/03/2013 06:25:33     01/03/2013 06:40:11         2

I want a result like this

ID  | Date          |       Total Duration
1       01/03/2013          Time in Minutes
1       02/03/2013          Time in Minutes
2       02/03/2013          Time in Minutes

There is a way to do this with linq using C#?

Upvotes: 3

Views: 1280

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Group items by date and id, and calculate sum of durations for each group:

var query = from r in records
            group r by new { r.Id, r.StartDate.Date } into g
            select new {
               g.Key.Id,
               g.Key.Date,
               TotalDuration = g.Sum(x => (x.EndDate - x.StartDate).TotalMinutes)
            };

Here is working program.

Upvotes: 5

Related Questions