简体   繁体   中英

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

Suppose I have two tables: Category and Product. I want use linq-to-sql to select all categories (with products) that have duplicated products. 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). How to modify the query?

It would be great to have Category name display somehow instead of 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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