c# - 使用 linq 按具有空数据值的日期进行分组

标签 c# asp.net linq

我正在使用 LINQ 按月对过去 12 个月的评分进行分组,并像这样输出 JSON:

var startDate = DateTime.Now.AddMonths(-13);

var ratings = db.Ratings
    .Where(x => x.RatingDate > startDate)
    .GroupBy(c => new { Year = c.RatingDate.Year, Month = c.RatingDate.Month })
    .ToList()
    .Select(c => new
    {
        Date = new DateTime(c.Key.Year, c.Key.Month, 1),
        Month = new DateTime(c.Key.Year, c.Key.Month, 1).ToString("MMM"),
        Average = c.Average(d => d.Rating)
    })
    .OrderBy(a => a.Date);

return Json(new
    {
        Average = ratings.Select(x=>x.Average),
        Dates = ratings.Select(x=>x.Month)
    });

如果我有 10 月和 11 月的数据,那么我的结果如下所示:

平均:[3.5, 4] 日期:[“十月”,“十一月”]

如何用 0 预填充前 12 个月?所以我应该得到 2015 年 12 月到 2016 年 11 月的结果,2015 年 12 月 -> 2016 年 9 月显示为 0。

最佳答案

这是另一种与您最终采用的方式非常相似的方式。

var now = DateTime.Now.AddDays(1 - DateTime.Now.Day);
var months = Enumerable.Range(-11, 12)
    .Select(m => new DateTime(now.AddMonths(m).Year, now.AddMonths(m).Month, 1));

var ratingsByMonth =
    from date in months
    let month = new { Year = date.Year, Month = date.Month }
    join r in ratings
    on month equals new { r.RatingDate.Year, r.RatingDate.Month }
    into g
    select new {
        Date = month,
        Rating = g.Count() > 0 ? g.Average(x => x.Rating) : 0
    };

关于c# - 使用 linq 按具有空数据值的日期进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838286/

相关文章:

生成 HTML 和 Excel 的 ASP.Net Web 服务器控件

c# - 在使用多个 Linq2 .... 上下文时,编译器如何确定使用哪个提供程序?

c# - LINQ to Entity Framework 多重连接与多个动态搜索条件

c# - 如果/如果否则/否则

asp.net - 父级 Div 有边距时文本框高度 100%

asp.net - 如何通过 FORM 从 ASP.Net MVC 堆栈调用存储过程并在 json 中返回它们?

c# - 带连接的 linq 查询返回不正确的值/关联

c# - 3D 屏幕保护程序干扰 WPF 应用程序 (Windows XP)

c# - 如果测试方法失败,如何使构建失败?

c# - 相同的代码返回不同的结果