我想的是:
ObjectQuery<Visit> visits = myentitys.Visits;
var uQuery =
from visit in visits
group visit by visit.ArrivalTime.Value.Day into g
select new
{
Day = g.Key,
Hours = g.Average(visit => (visit.LeaveTime.Value - visit.ArrivalTime.Value).TotalMinutes)
};
获取按日分组的访客的平均停留时间。
答案 0 :(得分:7)
假设您的后备存储是SQL Server,请执行以下操作。顺便说一句,我更正了我认为是一个拼写错误 - 你将一个总分钟数分配到一个名为Hours的字段中。为了未来的观众,我将该字段重命名为Minutes。
ObjectQuery<Visit> visits = myentitys.Visits;
var uQuery = from visit in visits
group visit by visit.ArrivalTime.Value.Day into g
select new
{
Day = g.Key,
Minutes = g.Average(visit => System.Data.Objects.SqlClient.SqlFunctions.DateDiff("m", visit.LeaveTime.Value, visit.ArrivalTime.Value))
};
令人失望的是LINQ to Entities不支持将DateTime减法内在转换为DateDiff,然后产生TimeSpan对象。
答案 1 :(得分:1)
我宁愿从数据库中获取数据,然后在内存中执行平均功能。尽管我不确定会对性能产生什么影响......
List<Visit> visits = myentitys.Visits.ToList();//Get the Visits entities you need in memory,
//of course,you can filter it here
var uQuery =
from visit in visits
group visit by visit.ArrivalTime.Value.Day into g
select new
{
Day = g.Key,
Hours = g.Average(visit => (visit.LeaveTime.Value - visit.ArrivalTime.Value).TotalMinutes)
};
这种算术运算无法在sql查询中进行转换(例如异常说:DbArithmeticExpression参数必须具有数字公共类型),但内存中的对象可以使用。
希望这会有所帮助。