Using npgsql, EF Core 3 and a PostgreSQL database, I am trying to write the following SQL query in LINQ.
SQL:
SELECT date("EndDate"), avg("EndDate"-"StartDate") as avg_time
FROM trip
group by date("EndDate")
LINQ:
var q = from trip in _context.Trips
group trip by trip.EndDate.Date into tripGroup
select new { date = tripGroup.Key, avg_time_mins = tripGroup.Average(tg => (tg.EndDate - tg.StartDate).TotalMinutes) };
I tried with TotalMinutes
, because .Average( )
does not seem to take a TimeSpan. All efforts ended up with a runtime exception stating that this construct is not supported and suggesting to rewrite the query.
If u want to TimeSpan as average using Linq(that what I understand from question) first u have to understand average will be done in memory.
var groups = await _context.Trips.GroupBy(trip =>trip.EndDate.Date).ToArrayAsync() // load Them in memory
var q = groups.Select(group=> {
var timeSpans = group.Select(trip=>trip.EndDate - trip.StartDate);
var avg = GetAverage(timeSpans)
return new {group.key, avg }
}).ToArray()
TimeSpan GetAverage(IEnumerable<TimeSpan> timeSpans){
var average= timeSpans.Average(x => x.TotalMilliseconds)
return TimeSpan.FromMilliseconds(average);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.