C#Linq找到重复的行

时间:2009-12-11 19:44:03

标签: c# linq

Name              City

Joe         Houston   
Jerry       London    
Alex        Houston   
Jerry       London    

如何使用LINQ返回重复行,如

的Sql

SELECT name, city, count(*)
FROM collection
GROUP BY name,city 
HAVING count(*) > 1

我尝试了一些东西

var qry =
                from m in context.Collections
                group m by new { m.city, m.name } into grp
                select new { rp = grp.Count() > 2 };

2 个答案:

答案 0 :(得分:14)

你需要一个地方,而不是一个选择:

var qry =  from m in context.Collections
           group m by new { m.city, m.name } into grp
           where grp.Count() > 1
           select grp.Key;

答案 1 :(得分:0)

@Jon Skeet 的答案为基础,使用“one liner”替代方案,返回重复值,而不仅仅是键:

var duplicates = db.Collections.GroupBy(a => new { m.city, m.name })
                               .Where(a => a.Count() > 1)
                               .SelectMany(a => a.ToList());