3

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

2 Answers 2

14

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Hi John,I want to ask question. Is it possible to select duplicate rows key and value?
1

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.