在C#中时间跨度之和 [英] sum of timespans in c#

查看:95
本文介绍了在C#中时间跨度之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包括时间跨度变量对象的集合:

I have a collection of objects that include a timespan variable:

MyObject
{ 
    TimeSpan TheDuration { get; set; }
}

我想使用LINQ来总结这些时间。
当然,(从MyCollection的R选择r.TheDuration).SUM();不行!

I want to use linq to sum those times. Of course, (from r in MyCollection select r.TheDuration).Sum(); doesn't work!

我想无力继续改变的数据类型为int,然后总结它和金额转换为时间跨度的。因为在我的收藏无力继续各自使用作为一个时间跨度别的地方那将是混乱的。

I'm thinking of changing the datatype of TheDuration to an int and then summing it and converting the sum to a TimeSpan. That'll be messy because each TheDuration in my collection is used in as a timespan somewhere else.

在此求和任何建议?

推荐答案

不幸的是,没有一个接受的总和过载 IEnumerable的<&TimeSpan的GT; 。此外,还有指定类型参数运营商基于通用的约束没有电流的方式,所以尽管时间跨度是原生可累加,这一事实不能轻易拾起由通用code。

Unfortunately, there isn't a an overload of Sum that accepts an IEnumerable<TimeSpan>. Additionally, there's no current way of specifying operator-based generic constraints for type-parameters, so even though TimeSpan is "natively" summable, that fact can't be picked up easily by generic code.

一个办法是,就像你说的,总结一体型相当于时间跨度,而不是,然后再打开的的总和成时间跨度一次。这个理想的属性是<一个href=\"http://msdn.microsoft.com/en-us/library/system.timespan.ticks.aspx\"><$c$c>TimeSpan.Ticks,其中往返准确。但它没有必要在所有的改变你的类属性型;你可以只项目的:

One option would be to, as you say, sum up an integral-type equivalent to the timespan instead, and then turn that sum into a TimeSpan again. The ideal property for this is TimeSpan.Ticks, which round-trips accurately. But it's not necessary to change the property-type on your class at all; you can just project:

var totalSpan = new TimeSpan(myCollection.Sum(r => r.TheDuration.Ticks));

另外,如果你想坚持的时间跨度的 + 运营商做加法,你可以使用总结运营商:

Alternatively, if you want to stick to the TimeSpan's + operator to do the summing, you can use the Aggregate operator:

var totalSpan = myCollection.Aggregate
                (TimeSpan.Zero, 
                (sumSoFar, nextMyObject) => sumSoFar + nextMyObject.TheDuration);

这篇关于在C#中时间跨度之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆