I'm trying to construct a query in LINQ/Entity Framework that will return all rows that have a duplicate based on one column. However, I don't want to group them, I actually want to get all the rows that have the duplicate.
name age
---- ---
john 15
john 16
jack 20
jill 26
sam 10
sam 12
How can I get a list of rows that have duplicates based on the name column? This is the resultset I'm expecting:
name age
---- ---
john 15
john 16
sam 10
sam 12
I tried something like this, but I think this will give me a grouped result I think:
var duplicates = Shop.GroupBy(r => r.Name)
.Where(x => x.Count() > 1)
.Select(val => val.Key);
Use SelectMany
:
var duplicates = Shop.GroupBy(r => r.Name)
.Where(x => x.Count() > 1)
.SelectMany(g=> g);
It will help you to flatten the result of each group that have more than one element in just one collection