2012-06-25 62 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(), 
    }; 

可能需要用它来摆弄了一下,但结构应该是合理的。