简体   繁体   中英

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. 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). Grouping examples, amongst others, can be found at 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. 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:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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