简体   繁体   English

LINQ和EntityFramework:在分组后得到第一个结果

[英]LINQ and EntityFramework: Getting first result after group by

What i have is the next table: 我有的是下一张桌子:

我的表

What im trying to do in LINQ using C# is to group by the Created column (ignoring the time!) and showing its counts next to each date so i could grab any top rows i want. 我在LINQ中使用C#尝试做的是按创建列分组(忽略时间!)并在每个日期旁边显示其计数,这样我就可以抓住我想要的任何顶行。 This query i got no problem doing in sql like the following way: 这个查询我在sql中做的没有问题,如下所示:

SELECT CAST(Created AS DATE) 'Created', COUNT(*) AS 'Count'
FROM Alert
GROUP BY CAST(Created AS DATE)
ORDER BY 'Count' DESC

which results with: 结果如下:

在此输入图像描述

but again, i'd like to do that in LINQ and simply all my tryouts failed, could anyone please guide me? 但是再一次,我想在LINQ中做到这一点,而我的所有试训都失败了,有人可以指导我吗?

Use the Date property of DateTime : 使用DateTimeDate属性:

var query = db.Alert
    .GroupBy(a => a.Created.Date)
    .Select(g => new { Created  = g.Key, Count = g.Count() })
    .OrderByDescending(x => x.Count);

It seems that Linq-To-Entities does not support the DateTime.Date property. 似乎Linq-To-Entities不支持DateTime.Date属性。 So you have to use DbFunctions.TruncateTime . 所以你必须使用DbFunctions.TruncateTime

Then this should work: 那应该工作:

var query = db.Alert
    .GroupBy(a => DbFunctions.TruncateTime(a.Created))
    .Select(g => new { Created  = g.Key, Count = g.Count() })
    .OrderByDescending(x => x.Count);

@TimSchmelter is right, but I would like to remind that in Linq you can do something like : @TimSchmelter是对的,但我想提醒一下,在Linq你可以这样做:

var multimap = db.Alert.ToLookup(o => o.Created.Date, o => o);

The count of items is just property of the value list you get when you use a date as a key. 项目数只是您使用日期作为键时获得的值列表的属性。

foreach(date in multimap.Select(g => g.Key).ToList()){
    var itemCount = multimap[date].Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM