如何选择在EF中按日期分组的多个计数

时间:2014-09-11 05:32:42

标签: c# entity-framework count linq-group

我的表格大致如下:

Date        | Category  | Name
01/02/2014  |    A      | Foo
01/02/2014  |    B      | Bar
02/02/2014  |    A      | Baz
02/02/2014  |    A      | Bla

我正在尝试构建一个产生类似内容的查询:

Date        | CategoryACount | CategoryBCount
01/02/2014  |       1        |      1
02/02/2014  |       2        |      0

我目前有存储过程循环遍历日期并通过逐个查询数据创建临时表,我们计划将所有应用程序逻辑从存储过程中移出。

如何在EF中生成此查询?

1 个答案:

答案 0 :(得分:4)

如果你的表看起来像这样

public class Table
{
   public DateTime Date { get; set; }
   public string  Category { get; set; }
   public string Name { get; set; }
}

你可以使用这样的查询:

db.Table.GroupBy(c => c.Date)
        .Select(c => new 
                 {
                  Date = c.Key,
                  CatA = c.Where(q => q.Category == "A").Count(),
                  CatB = c.Where(q => q.Category == "B").Count(),
                  })

要测试它 - 使用LinqPad并运行:

var lst = new List<Table>();

lst.Add(new Table(){Date = new DateTime(2014,2,1),Category = "A"});
lst.Add(new Table(){Date = new DateTime(2014,2,1),Category = "B"});
lst.Add(new Table(){Date = new DateTime(2014,2,2),Category = "A"});
lst.Add(new Table(){Date = new DateTime(2014,2,2),Category = "A"});


lst.GroupBy(c => c.Date)
   .Select(c => new {
         Date = c.Key,
         CatA = c.Where(q => q.Category == "A").Count(),
         CatB = c.Where(q => q.Category == "B").Count(),
          })
   .Dump();

enter image description here