简体   繁体   English

如何使用linq-to-sql group by列出重复的记录?

[英]How to use linq-to-sql group by to list duplicated records?

Suppose I have two tables: Category and Product. 假设我有两个表:Category和Product。 I want use linq-to-sql to select all categories (with products) that have duplicated products. 我想使用linq-to-sql选择具有重复产品的所有类别(与产品一起)。 My query goes like this: 我的查询是这样的:

from p in db.Products
group p by p.CategoryId into c
select new 
{
 categoryId = c.Key,
 products = from PbyC in c 
 group PbyC by PbyC.Name into dupl
 where dupl.Count() > 1
 select dupl;
}

It works but LINQPad lists empty Categories (without any duplicated Product). 它可以工作,但是LINQPad列出了空的类别(没有任何重复的产品)。 How to modify the query? 如何修改查询?

It would be great to have Category name display somehow instead of Id. 最好以某种方式显示类别名称而不是ID。

EDIT: I have relationship between tables. 编辑:我有表之间的关系。

db.Products.GroupBy(p => new { p.Name, p.CategoryId })
           .Select(g => new { g.Key.CategoryId, Count = g.Count })
           .Where(ng => ng.Count > 1)
           .Select(ng => ng.CategoryId);

That'll select the ids of the categories with more than one Product of the same name, and is assuming you don't have any relationships set up between the objects so you'll need to join the results to the Categories table to get detailed info. 这将选择具有多个同名产品的类别的ID,并假设您在对象之间未设置任何关系,因此您需要将结果添加到“ Categories表中以获取详细信息信息。

If you do have a relationship set up then you can always change the CategoryId to Category (or whatever the related object is named) and just select Category.Name in the last Select . 如果您确实设置了关系,则可以始终将CategoryId更改为Category (或任何相关的对象命名),然后在最后一个Select选择Category.Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM