开发者

Finding duplicate row using Linq

开发者 https://www.devze.com 2022-12-13 16:53 出处:网络
Person NameCity JoeHouston JerryLondon AlexHouston JerryLondon How to return duplicate row using LINQlike Sql

Person

Name        City

Joe         Houston   
Jerry       London    
Alex        Houston   
Jerry       London    

How to return duplicate row using LINQ like

Sql

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

I tried something

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


You need a where, not a select:

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


Building on @Jon Skeet's answer with a "one liner" alternative that returns the duplicate values, not just the keys:

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

精彩评论

暂无评论...
验证码 换一张
取 消