Prince Ashitaka
Prince Ashitaka

Reputation: 8773

How to find Sum of DateTime using LINQ

I have a collection of class with a DateTime Property, I would like to get sum of Minutes and Seconds. Is there any easy way to do this using LINQ without manually summing the minutes and seconds?

Upvotes: 3

Views: 4363

Answers (2)

Stuart
Stuart

Reputation: 66882

+1 for Stephen's answers.

Just for fun... if you really do want "to get sum of Minutes and Seconds" then:

 class MyClass
 {
     public DateTime DateTimeMember {get;set;}
     // other stuff
 }


 var myObjects = new List<MyClass>();

 // fill list...

 // 3 possible things you might be interested in
 var myMinuteSum = myObjects.Sum(x => x.DateTimeMember.Minute);
 var mySecondSum = myObjects.Sum(x => x.DateTimeMember.Second);     
 var myOddTotalOfMinutesAndSecondsInSeconds = myObjects.Sum(x => x.DateTimeMember.Minute * 60 + x.DateTimeMember.Second);

Upvotes: 3

Stephen Chung
Stephen Chung

Reputation: 14605

I suppose you mean TimeSpan instead of DateTime? You can't add DateTime's...

To sum TimeSpan's:

  1. list.Sum(span => span.TotalSeconds) ==> total seconds

  2. TimeSpan.FromSeconds(...) ==> Convert total seconds back to time span

You can then use properties in TimeSpan to reformat it back to hours, minutes, seconds etc.

Upvotes: 8

Related Questions