tags:

views:

26

answers:

1

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.

A: 
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.

Dave
I have relationship between tables.
jlp