2012-06-25 63 views
1

我有一個場景,我需要檢索按日期時間字段的月份分組的對象計數。Linq - 按前12個月的日期時間組 - 包括空月

我發現下面的帖子裏面讓我的存在方式的一部分...

Linq: group by year and month, and manage empty months

...但我需要列出從今天的日期前12個月和對象爲計數每個月,這是我掙扎的地方。

我見過幾個其他職位類似問題/解決方案,但我選擇了,因爲它也產生任何個月的記錄與任何幫助的0

感謝計數的要求,上述一個我可以得到這個。

編輯

OK,我遠一點感謝Enigmativity(感謝您抽出寶貴的時間!):

var news = from s in db.NewsItems 
        where s.SubmittedDate > first 
        select new 
        { 
         Date = s.SubmittedDate, 
         Title = s.Title, 
        }; 

var grouping = from g in news.AsEnumerable() 
         select new NewsCountCollection 
         (
          g.Date, 
          g.Title 
         ); 

var lookup = grouping.ToLookup(x => x.Month, x => x.Title); 

var counts = from n in Enumerable.Range(-11, 12) 
        let Month = last.AddMonths(n) 
        select new 
        { 
         Month, 
         Count = lookup[Month].Count(), 
        }; 

var countList = from c in counts.AsEnumerable() 
         select new NewsCountMonthList 
         (
          c.Month.ToString("MMMM"), 
          c.Count 
         ); 

...及以下

public class NewsCountCollection 
{ 
    public DateTime Month { get; set; } 
    public string Title { get; set; } 

    public NewsCountCollection(DateTime date, string title) 
    { 
     this.Month = new DateTime(date.Year, date.Month, 1); 
     this.Title = title; 
    } 

} 

public class NewsCountMonthList 
{ 
    public string Month { get; set; } 
    public int Count { get; set; } 

    public NewsCountMonthList(string month, int count) 
    { 
     this.Month = month; 
     this.Count = count; 
    } 
} 

......雖然似乎效率很低......但我不禁想到必須有比這更好的方法。我在正確的軌道上嗎?

+0

請發佈您嘗試過的代碼,您正在處理的對象結構以及任何示例數據。 –

回答

2

這應該爲你做它:

var now = DateTime.Now; 
var last = new DateTime(now.Year, now.Month, 1); 
var first = last.AddMonths(-12); 

var query = 
    from s in somethings 
    where s.DateTimeField >= first 
    where s.DateTimeField < last 
    select new 
    { 
     Month = new DateTime(s.DateTimeField.Year, s.DateTimeField.Month, 1), 
     Something = s, 
    }; 

var lookup = query.ToLookup(x => x.Month, x => x.Something); 

var counts = 
    from n in Enumerable.Range(-12, 12) 
    let Month = last.AddMonths(n) 
    select new 
    { 
     Month, 
     Count = lookup[Month].Count(), 
    }; 

可能需要用它來擺弄了一下,但結構應該是合理的。