Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to find duplicates but get 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 the duplicates in a table based on addr1 and addr2. The only problem with this code is that it only gives me the pair of addr1 and addr2 that are duplicates when i actually want to display all the fields of the records. ( all the fields like ID, addr1, addr2, city, state...)

Any ideas ?

like image 307
Nathan Avatar asked Apr 01 '13 16:04

Nathan


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()});
like image 188
Ilya Ivanov Avatar answered Oct 24 '22 00:10

Ilya Ivanov


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 duplicate groups

like image 39
cuongle Avatar answered Oct 24 '22 01:10

cuongle