使用LINQ查找/删除重复项 [英] Using LINQ to find / delete duplicates

查看:92
本文介绍了使用LINQ查找/删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一堆重复项的表.这些是精确的重复项,减去主键列,该列是整数标识列.

I have a table that contains a bunch of duplicates. These are exact duplicates, minus the primary key column, which is an integer identity column.

使用EF和LINQ,我如何找到重复项并删除它们,只剩下一个副本.

Using EF and LINQ, how do I find the duplicates and delete them, leaving only one copy.

我发现使用SQL和SSMS的重复项和计数.我只是不知道从LINQ开始.

I found the duplicates and a count of each using SQL and SSMS. I'm just don't know where to start with LINQ.

谢谢!

推荐答案

离我远去(未经测试):

Off the top of my head (untested):

var q = from r in Context.Table
        group r by new { FieldA = r.FieldA, FieldB = r.FieldB, // ...
            into g
        where g.Count() > 1
        select g;
foreach (var g in q)
{
    var dupes = g.Skip(1).ToList();
    foreach (var record in dupes)
    {
        Context.DeleteObject(record);
    }
}
Context.SaveChanges();

这篇关于使用LINQ查找/删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆