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

时间:2014-01-21 06:12:54

标签: c# entity-framework

我想从链接到Entity Framework 4.0的表中获取前五个最重复的记录。如何在单个查询中返回五个记录的集合列表?

2 个答案:

答案 0 :(得分:8)

您只需按计数分组,按顺序递减,然后按(5)。可以在101 LINQ Samples找到分组示例等。

答案 1 :(得分:4)

实际上,您应该按字段进行分组,这些字段定义记录是否重复。例如。在你的情况下,它应该像会员ID。然后,您可以引入新的范围变量,该变量将保留每个组中的记录数。使用该变量来排序结果:

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
            };

然后先拿5:

 var top5 = query.Take(5);

这将生成类似

的查询
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