实体框架组按最大日期和计数 [英] Entity Framework Group By with Max Date and count
本文介绍了实体框架组按最大日期和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下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复制该查询的输出。
I'm trying to replicate the output of that query using 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查询相比,执行时间相当长。关于如何优化我的方法的任何建议?
But takes horribly long to execute compared to the raw SQL query. Any suggestions on how to optimise my approach? It somehow feels wrong.
推荐答案
如果您想要一个最大值,请使用 Max()
Linq方法:
If you want a max, use the Max()
Linq method:
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);
这篇关于实体框架组按最大日期和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文