我有物品的物品:
public int ClientId {get;set;}
public DateTime StartDateTime{get;set;}
public DateTime EndDateTime{get;set;}
我想计算每个客户端与group by的所有日期时间之间的差异总和,但是这样:
var retVal = (from t items group t by ClientId into z
select new
{
ClientId = z.Key,
TimeSpanClientTotal = z.Sum(h => (h.EndDateTime - h.StartDateTime))
}).ToList();
由于Sum不能很好地用于TimeSpan,这是两个DateTimes对象之间差异的返回值,因此不起作用.
任何建议如何获得每个客户的总TimeSpan?
谢谢
解决方法:
Enumerable.Sum只是你在IEnumerable上调用的扩展方法.没有什么特别的,所以你可以轻松地创建另一个时间扩展的扩展方法:
static class TimeSpanExtensions
{
public static TimeSpan Sum<TSource>(this IEnumerable<TSource> enumerable,
Func<TSource,TimeSpan?> func )
{
return enumerable.Aggregate(TimeSpan.Zero, (total, it) =>
total+=(func(it)??TimeSpan.Zero);
}
}
假设你的班级定义是
class Record
{
public int ClientId { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
public Record(int clientId, DateTime startDateTime, DateTime endDateTime)
{
ClientId = clientId;
StartDateTime = startDateTime;
EndDateTime = endDateTime;
}
}
您可以编写与数字类型相同的代码:
var items = new[] {
new Record(1, DateTime.Now, DateTime.Now.AddHours(1)),
new Record(1, DateTime.Now, DateTime.Now.AddHours(1)),
new Record(1, DateTime.Now, DateTime.Now.AddHours(1))};
var total=items.Sum(h=>(h.EndDateTime-h.StartDateTime));
var grouped= (from t in items
group t by t.ClientId into z
select new
{
ClientId = z.Key,
TimeSpanClientTotal = z.Sum(h => (h.EndDateTime - h.StartDateTime))
}).ToList();
您也可以直接使用Enumerable.Aggregate:
var total= items.Aggregate(TimeSpan.Zero, (current, it) =>
current += (it.EndDateTime-it.StartDateTime));
代码可能更丑,但你可以做的不仅仅是简单的添加.