简体   繁体   English

获取Entity Framework中最重复的前五项记录

[英]Get top five most repeating records in Entity Framework

I want to get top five most repeating records from a table in link to Entity Framework 4.0. 我想从链接到Entity Framework 4.0的表中获得前五名最重复的记录。 How it can be possible in a single query which returns a list of collection of five records? 如何在单个查询中返回五个记录的集合列表呢?

You simply group by count, order descending by count and then Take(5). 您只需按计数分组,按计数降序,然后使用Take(5)。 Grouping examples, amongst others, can be found at 101 LINQ Samples . 分组示例以及其他示例,可以在101 LINQ Samples中找到。

Actually you should group by fields which define whether record is repeating or not. 实际上,您应该按定义记录是否重复的字段分组。 Eg in your case it should be something like member id. 例如,在您的情况下,该名称应类似于会员ID。 Then you can introduce new range variable which will keep number of records in each group. 然后,您可以引入新的范围变量,该变量将保留每个组中的记录数。 Use that variable for ordering results: 使用该变量来排序结果:

var query = from s in db.Statistics
            group s by s.MemberId into g  // group by member Id
            let loginsCount = g.Count()  // get count of entries for each member
            orderby loginsCount descending // order by entries count
            select new { // create new anonymous object with all data you need
                MemberId = g.Key,
                LoginsCount = loginsCount
            };

Then take first 5: 然后先取5:

 var top5 = query.Take(5);

That will generate query like 那将生成查询

SELECT TOP (5)                               // Take(5)
[GroupBy1].[K1] AS [MemberId],               // new { MemberId, LoginsCount }
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
        [Extent1].[MemberId] AS [K1],
        COUNT(1) AS [A1]                     // let loginsCount = g.Count()
        FROM [dbo].[Statistics] AS [Extent1]
        GROUP BY [Extent1].[MemberId]        // group s by s.MemberId
)  AS [GroupBy1]
ORDER BY [GroupBy1].[A1] DESC                // orderby loginsCount descending

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

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