# Sum Datetime total hours

• ### Question

• Hello to all,

I have list which contains three variables Id-int,IdVehicle-int and DateTimeMade-DateTime.

I want with Linq to get sum of hours for some period.

Something like this:

var sumHours = _db.NameOfTheList.Where(x=>x.DateTimeMade > dateTimeFrom && x.DateTimeMade < dateTimeTo);

How to make sum of hours in this query?

Thanks a lot

Thursday, June 14, 2012 12:24 PM

### Answers

• ``` var what = (from x in _db where x.DateTimeMade > dateTimeFrom && x.DateTimeMade < dateTimeTo
group x by x.someId
into xx
select new{
id = (from xxx in xx select xxx.someId).Distinct(),
maxdate = (from xxx in xx select xxx.DateTimeMade).Max(),
mindate = (from xxx in xx select xxx.DateTimeMade).Min()
});```
You may enhance on that.
• Proposed as answer by Monday, June 18, 2012 4:52 AM
• Marked as answer by Monday, June 25, 2012 3:21 AM
Friday, June 15, 2012 3:36 AM

### All replies

• hello

summing DateTime is not usual, I'm not even sur it can be done.

You can sum Int, Decimal, Time... with a Linq syntaxe like :

var sumHours = _db.NameOfTheList.Where(x=>x.DateTimeMade > dateTimeFrom && x.DateTimeMade < dateTimeTo).Sum(x =>x.FieldToBeAggregated);

Sincerely

thierry

Thursday, June 14, 2012 1:02 PM
• Yeah, i know that. But i think that i read somewhere about this but im not sure.

Thanks

Thursday, June 14, 2012 1:13 PM
• ``` var what = (from x in _db where x.DateTimeMade > dateTimeFrom && x.DateTimeMade < dateTimeTo
group x by x.someId
into xx
select new{
id = (from xxx in xx select xxx.someId).Distinct(),
maxdate = (from xxx in xx select xxx.DateTimeMade).Max(),
mindate = (from xxx in xx select xxx.DateTimeMade).Min()
});```
You may enhance on that.
• Proposed as answer by Monday, June 18, 2012 4:52 AM
• Marked as answer by Monday, June 25, 2012 3:21 AM
Friday, June 15, 2012 3:36 AM
• Hi thierry schmit,

Welcome to MSDN Forum.

@tinmgaye has provided the code which can help to query out the max date and the min date, we can get the sum hours by substraction operation with the maxdate and mindate.

Best Regards

Allen Li [MSFT]
MSDN Community Support | Feedback to us

Monday, June 18, 2012 4:52 AM
• Hi Bogdan Nichovski,

Any update about this issue? If you need further help, please feel free to let me know.

Best Regards

Allen Li [MSFT]
MSDN Community Support | Feedback to us

Thursday, June 21, 2012 2:29 AM
• Sorry i was on holiday and i didn't see the answers. Thanks a lot, that is the answer that i need.

Best Regards

Monday, June 25, 2012 8:27 AM