如何显示每个月,即使本月没有数据

时间:2016-02-22 20:49:01

标签: c# linq charts

查询工作正常,除了它只提取一个月有超过零事件的值,例如,如果1月没有值,则它不显示1月。我想展示几个月。

var result = tIncidentReportings
    .AsEnumerable()
    .GroupBy(c => c.Date.ToString("MMM"))
    .Select(g => new { Month = g.Key, Count = g.Count() })
    .OrderBy(x => DateTime.ParseExact((x.Month).ToString(), "MMM", CultureInfo.InvariantCulture));

1 个答案:

答案 0 :(得分:1)

问题是,无论几个月没有任何报告,你都会错过几个月。您必须检查哪些月份没有,并手动添加。

var result = tIncidentReportings
    .AsEnumerable()
    .GroupBy(c => c.Date.ToString("MMM"))
    .Select(g => new { Month = g.Key, Count = g.Count() })
    .OrderBy(x => DateTime.ParseExact((x.Month).ToString(), "MMM", CultureInfo.InvariantCulture));
var months = 
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthGenitiveNames.Select(s => s.Substring(0,3)).ToList();
months.foreach(m => {
    if(!results.Select(r => r.Month).Contains(m)){
        results.Add(new {Month = m, Count = 0};
});

像这样的东西

或重写:

var months = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthGenitiveNames.Select(s => s.Substring(0,3)).ToList();
var reports = months.Select(m => 
    new { 
        Month = m, 
        Count = tIncidentReportings.AsEnumerable().Where(i => i.Date.ToString("MMM") == m).Count()
    }
).OrderBy(x => DateTime.ParseExact((x.Month).ToString(), "MMM", CultureInfo.InvariantCulture)).ToList();