Using Linq to find duplicates, but getting the whole record

So i am using this code

var duplicates = mg.GroupBy(i => new { i.addr1, i.addr2 }) .Where(g => g.Count() > 1) .Select(g=>g.Key); GridView1.DataSource = duplicates; GridView1.DataBind(); 

to find and list duplicates in a table based on addr1 and addr2. The only problem with this code is that it only gives me a pair of addr1 and addr2 that are duplicated when I really want to display all the record fields. (all fields, such as ID, addr1, addr2, city, state ...)

Any ideas?

+6
source share
2 answers

To get all values, you can use ToList() on IGrouping

 var duplicates = mg.GroupBy(i => new { i.addr1, i.addr2 }) .Where(g => g.Count() > 1) .Select(g => new {g.Key, Values = g.ToList()}); 
+13
source

You should use First() instead of Key :

 var duplicates = mg.GroupBy(i => new { i.addr1, i.addr2 }) .Where(g => g.Count() > 1) .Select(g => g.First()); 

It returns the first row of each repeating group

+8
source

All Articles