簡體   English   中英

即使本月沒有數據,如何顯示每個月

[英]How to display each month, even if no data for this month

該查詢工作正常,只是它僅在一個月發生的事件多於零的情況下才拉取該值,例如,如果一月沒有值,則不顯示一月。 我想展示所有的幾個月。

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 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM