c# - LINQ Group By with subquery -
i trying make query on linq using groupby, on select statement try make kind of subquery. idea have 7 days for, need average value of these last 7 days current value current day. have tried following code:
var odate = datetime.utcnow; var startdate = odate.addworkingdays(-7); var enddate = odate.addworkingdays(-1); var races = racetimes.where( x => x.odate >= startdate && x.odate <= odate && x.status == "finished") .groupby(x => x.athletes.name).select(x => new { name = x.key, description = "just random description now", odate = odate, sevendaysavg = (int?)x.where(y => y.odate >= startdate && y.odate <= enddate).average(y => sqlfunctions.datediff("s", y.starttime, y.endtime)), racetime = (int?)x.where(y => y.odate == odate).average(y => sqlfunctions.datediff("s", y.starttime, y.endtime)) }).tolist().where(x => x.racetime!= null).tolist();
the sevendaysavg (average) works fine, returns me average of last 7 days races. however, latency returning me null.
i trying make translation of query sql, works fine:
... avg(case when h.odate between '20140219' , '20140227' datediff(second, h.starttime, h.endtime) else null end) sevendaysavg, avg(case when h.odate = '20140227' datediff(second, h.starttime, h.endtime) else null end) racetime, ...
so doing wrong in linq query? doing not possible? i've tried aproach. first calculate averages, , in main query have like:
sevendaysavg = averages.where(y => y.name== x.athletes.name).select(y => y.sevendaysavg).firstordefault()
once again, approach didnt work, keeps giving me empty results. whats wrong here?
Comments
Post a Comment