且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找SQL表中的所有重复记录与实体框架

更新时间:2022-11-13 16:36:56

如果您使用实体框架我假设你使用LINQ以及

If you use Entity Framework I assume you use LINQ as well.

在这种情况下,尝试这种方式:

In which case, try it this way:

var duplicates = Shop.GroupBy(i => i.Name)
                     .Where(x => x.Count() > 1)
                     .Select(val => val.Key);

foreach(var item in duplicates)
{
    //process
}

在一个简单的例子,输出应该是这样的:
查找SQL表中的所有重复记录与实体框架

In a simple example the output would look like this:

//编辑:

如果你想组由多个列,你可以使用这个语法:

if you want to group by multiple columns you can use this syntax:

var query = (from sh in Shop
     group sh by new {sh.Name, sh.Address, sh.City} into grp
     select new
     {
        name = grp.Key.Name,
        address = grp.Key.Address,
        city = grp.Key.City
     }).ToList()
       .GroupBy(q => q.name)
       .Where (q => q.Count() >1)
       .Dump();

这将导致以下内容:

查找SQL表中的所有重复记录与实体框架

// EDIT2
有时我很愚蠢的边缘。
继KISS原则:

// sometimes I am borderline stupid. Following the KISS-principle:

var query = Shop.GroupBy (s => s.Name).Where (s => s.Count () > 1).Dump();