需要帮助Linq Query Group By + Count

时间:2012-06-29 09:56:02

标签: c# linq

我有以下表格,其中包含ActivityLog的记录:

ID, UserId,      Category,   Created
1       11     DeAssigned    05/10/2012
2       11          LogIn    05/11/2012
3       20       Assigned    06/15/2012
4       11       Assigned    06/10/2012
5       20     DeAssigned    06/13/2012
6       20       Assigned    07/12/2012
7       11     DeAssigned    07/16/2012
8       20       Assigned    08/15/2012
...

现在我希望查询表格以创建相同的结构相同的结果,例如

var data = new[] { 
                    new { Month = "05", Assigned = 14, DeAssigned = 5, LogIn=1 },
                    new { Month = "06", Assigned = 5, DeAssigned = 2, LogIn=0 },
                    new { Month = "07", Assigned = 50, DeAssigned = 8, LogIn=0 },
                    new { Month = "08", Assigned = 15, DeAssigned = 1, LogIn=0 }
};

我取得的成就:

var result = (from l in repoA.GetAll()
                      where   l.Created >= System.DateTime.Now.AddYears(-1)
                      group l by new { l.Created.Value.Month, l.Category }
                      into groups
                      orderby  groups.Key.Month 
                      select new
                                 {
                                     Month = groups.Key.Month,
                                     Category = groups.Key.Category,
                                     Count = groups.Count()
                                 });

没有最佳结果,但计算按月分组的所有活动:

 [0] {Month = 6, Category = Assigned, Count = 2}
 [0] {Month = 6, Category = Designed, Count = 1}
 [0] {Month = 6, Category = LogIn, Count = 1}
 [0] {Month = 7, Category = Assigned, Count = 3}

如何查询我的表格以“水平计数”格式格式化我的结果?

1 个答案:

答案 0 :(得分:2)

或更简单:

var result = (from l in repoA.GetAll()
                           where   l.Created >= System.DateTime.Now.AddYears(-1) 
                           group l by l.Created.Month into groups
                           orderby groups.Key ascending
                           select new
                              {
                                  Month = groups.Key,
                                  Assigned = groups.Where(g => g.Category == "Assigned").Count(),
                                  Deassigned = groups.Where(g => g.Category == "DeAssigned").Count(),
                                  LogIn = groups.Where(g => g.Category == "LogIn").Count()
                              });