查找SQL表中的所有重复记录与实体框架 [英] Find all duplicate records in SQL table with Entity Framework
本文介绍了查找SQL表中的所有重复记录与实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要创建一个包含所有与当时相同的名称记录的数据网格
I want to create a datagrid which contains all the records with then same name.
我有这个表:
Shop
ID name adress city
-----------------------------------------
1 name1 adress 1 city1
2 name 2 adress2 city2
3 name 2
4 name 2 city2
5 name 3
6 name 4 adress4 city4
7 name 4 adress4 city4
和我的DataGrid中必须包含以下内容:
and my datagrid must contain:
2 name 2 adress2 city2
3 name 2
4 name 2 city2
6 name 4 adress4 city4
7 name 4 adress4 city4
但我不知道如何来创建此查询
but I have no idea how to create this query
推荐答案
如果您使用实体框架我假设你使用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
}
在一个简单的例子,输出应该是这样的:
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();
这将导致以下内容:
// EDIT2
有时我很愚蠢的边缘。
继KISS原则:
// sometimes I am borderline stupid. Following the KISS-principle:
var query = Shop.GroupBy (s => s.Name).Where (s => s.Count () > 1).Dump();
这篇关于查找SQL表中的所有重复记录与实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文