How to sum Timespan of subtraction between two datetimes in Linq when using group by?
Enumerable.Sum is just an extension method you call on an IEnumerable. There is nothing special to it so you can easily create another extension method that sums timespans:
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);
}
}
Assuming your class definition is
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;
}
}
You can write the same code you would for the numeric types:
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();
You can also use Enumerable.Aggregate directly:
var total= items.Aggregate(TimeSpan.Zero, (current, it) =>
current += (it.EndDateTime-it.StartDateTime));
The code can be uglier but you can do a lot more than simple addition.