实体框架组具有最大日期和计数

Mic*_*rys 6 c# sql linq entity-framework

我有以下SQL

SELECT  Tag , COUNT(*) , MAX(CreatedDate)
FROM    dbo.tblTags
GROUP BY Tag
Run Code Online (Sandbox Code Playgroud)

其中输出如下:

+-----------------+------------------+-------------------------+
|       Tag       | (No column name) |    (No column name)     |
+-----------------+------------------+-------------------------+
| a great tag     |                1 | 2015-04-01 18:30:31.623 |
| not a test      |                1 | 2015-04-01 17:46:09.360 |
| test            |                5 | 2015-04-01 18:13:17.920 |
| test2           |                1 | 2013-03-07 16:53:54.217 |
+-----------------+------------------+-------------------------+
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用EntityFramework复制该查询的输出.

我有以下逻辑可行:

    var GroupedTags = Tags.GroupBy(c => c.Tag)
        .Select(g => new 
        { 
            name = g.Key, 
            count = g.Count(), 
            date = g.OrderByDescending(gt => gt.CreatedDate).FirstOrDefault().CreatedDate 
        })
        .OrderBy(c => c.name);
Run Code Online (Sandbox Code Playgroud)

但与原始SQL查询相比,执行时间非常长.关于如何优化我的方法的任何建议?它有点不对劲.

DLe*_*Leh 13

如果您想要最大值,请使用Max()Linq方法:

var GroupedTags = Tags.GroupBy(c => c.Tag)
    .Select(g => new 
    { 
        name = g.Key, 
        count = g.Count(), 
        date = g.Max(x => x.CreatedDate)
    })
    .OrderBy(c => c.name);
Run Code Online (Sandbox Code Playgroud)