0

我编写了以下 LINQ-to-SQL 以使我能够获取每天的记录总数。

为了满足我的需要,我想对其进行一些修改。我进行了各种尝试,但始终无法做到正确。

我想列出过去 9 天,即使在此期间没有“打开”。我还想按日/月分组,而不是像下面那样仅按日分组。

我希望得到的输出示例是:

DateString   Opens
===================
 9/5         0
10/5         0
11/5         3

ETC...

public List<OpensOverTimeViewModel> GetOpensOverTimeViewModel(int eId)
{

    DateTime lastDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-9);
    DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1);

    var summary = (from p in db.Opens
                    where (p.ElementId == eId) && (p.Timestamp >= lastDate) && (p.Timestamp <= currentDate)
                    let k = new
                    {
                        Day = p.Timestamp.Day
                    }
                    group p by k into t
                    select new OpensOverTimeViewModel
                    {
                        DateString = t.Key.Day,
                        TotalOpens = t.Count(),
                        ElementName = ""
                    }).ToList();

    return summary;
}

任何有关如何最好地解决此问题的帮助将不胜感激。

4

1 回答 1

1

从数据库中取回结果后,您可以在代码中创建左连接

将下面的行放在您的return summary;行之前。

var allDates = from idx in Enumerable.Range(0, (currentDate - lastDate).Days)
               select lastDate.AddDays(idx);

summary = (
          from allDate in allDates
          join su in summary on allDate.Day equals su.DateString into x
          from su in x.DefaultIfEmpty()
          select new OpensOverTimeViewModel
          {
              DateString = allDate.Day,
              TotalOpens = su == null ? 0 : su.TotalOpens,
              ElementName = ""
          }).ToList();

要按天/月分组,我建议使用整个日期,t.Key.Day替换为.t.Key.DateDateStringDateTime

于 2012-06-12T04:17:19.960 回答