我有以下SQL
SELECT Tag , COUNT(*) , MAX(CreatedDate) FROM dbo.tblTags GROUP BY Tag
输出以下内容:
+-----------------+------------------+-------------------------+ | 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 | +-----------------+------------------+-------------------------+
我正在尝试使用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);
但是与原始SQL查询相比,执行时间要长得多。关于如何优化我的方法的任何建议?感觉不对。
如果需要最大值,请使用Max()Linq方法:
Max()
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);