[英]Sorting grouped query in chronological order in LINQ query
The following LINQ query obtains the previous 12 months data and aggregates it by month. 以下LINQ查询获取前12个月的数据并按月汇总。
I'd like to order this in chronological order, with the current month being the most recent in the query. 我想按时间顺序排序,当前月份是查询中最近的月份。
What's the best way to achieve this? 实现此目标的最佳方法是什么?
public IEnumerable<EventMonthlySummaryMonthly> GetLastYearEventGrid()
{
DateTime currentDate = DateTime.Now.AddYears(-1).AddMilliseconds(1);
var summary = from p in db.Events
where (p.StartDate > currentDate) && (p.StartDate != null)
let k = new
{
Month = p.StartDate.Month
}
group p by k into t
select new EventMonthlySummaryMonthly
{
Month = t.Key.Month,
EventsWhatsOn = t.Count(p => p.EventTypeId == 1),
EventsRegular = t.Count(p => p.EventTypeId == 2),
EventsExhibitions = t.Count(p => p.EventTypeId == 3),
EventsAll = t.Count(p => p.EventTypeId != null),
};
return summary;
}
By sorting on the max date from the grouped month Descending. 通过对分组月份“降序”中的最大日期进行排序。 If the range spans several years this will give you the months that contains the latest dates first. 如果范围跨越数年,则将首先为您提供包含最新日期的月份。
orderby t.Max(p => p.StartDate) descending
select new EventMonthlySummaryMonthly
{
Month = t.Key.Month,
EventsWhatsOn = t.Count(p => p.EventTypeId == 1),
EventsRegular = t.Count(p => p.EventTypeId == 2),
EventsExhibitions = t.Count(p => p.EventTypeId == 3),
EventsAll = t.Count(p => p.EventTypeId != null),
}
public IEnumerable<EventMonthlySummaryMonthly> GetLastYearEventGrid()
{
DateTime currentDate = DateTime.Now.AddYears(-1).AddMilliseconds(1);
var summary = (from p in db.Events
where (p.StartDate > currentDate) && (p.StartDate != null)
let k = new
{
Month = p.StartDate.Month
}
group p by k into t
select new EventMonthlySummaryMonthly
{
Month = t.Key.Month,
EventsWhatsOn = t.Count(p => p.EventTypeId == 1),
EventsRegular = t.Count(p => p.EventTypeId == 2),
EventsExhibitions = t.Count(p => p.EventTypeId == 3),
EventsAll = t.Count(p => p.EventTypeId != null),
}).OrderByDescending(item=>item.Month);
return summary;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.