在LINQ查询中按时间顺序对分组查询进行排序

时间:2012-02-11 13:03:03

标签: c# linq linq-to-sql

以下LINQ查询获取前12个月的数据并按月汇总。

我想按时间顺序订购,当前月份是查询中最新的月份。

实现这一目标的最佳方式是什么?

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;
        }

2 个答案:

答案 0 :(得分:1)

通过对分组月份Descending的最大日期进行排序。如果范围跨越几年,这将为您提供包含最新日期的月份。

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),
}

答案 1 :(得分:0)

    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;
    }