Using Linq to find duplicates but get the whole record

…衆ロ難τιáo~ 提交于 2020-01-02 02:19:19

问题


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 ?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/15747220/using-linq-to-find-duplicates-but-get-the-whole-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!