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:
list.Sum(span => span.TotalSeconds) ==> total seconds
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);
精彩评论