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

编程入门 行业动态 更新时间:2024-10-11 23:18:32
本文介绍了使用实体框架查找SQL表中的所有重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个表:

商店 ID名称地址城市 ------------------------ ----------------- 1 name1地址1 city1 2名称2 adress2 city2 3名称2 4名称2 city2 5名称3 6名称4 adress4 city4 7名称4 adress4 city4

,我的datagrid必须包含:

2名称2 adress2 city2 3名称2 4名称2 city2 6名称4 adress4 city4 7名称4 adress4 city4

但是我不知道如何创建这个查询

解决方案

如果你使用Entity Framework我假设你使用LINQ作为在这种情况下,请尝试以下方式:

var duplicateates = Shop.GroupBy(i => i.Name) .Where(x => x.Count()> 1) .Select(val => val.Key); foreach(重复的var项目) { //进程}

在一个简单的示例中,输出将如下所示:

//编辑:

通过多个列可以使用以下语法:

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原则:

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

I want to create a datagrid which contains all the records with then same name.

I have this table:

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

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

解决方案

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:

//EDIT:

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

This will result in the following:

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

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

更多推荐

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

本文发布于:2023-11-25 11:09:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!