开发者

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:

f开发者_高级运维rom 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜