开发者

How to find Sum of DateTime using LINQ

I have a 开发者_JS百科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?


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.


+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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜