I’m trying to group by categories;
let’s say that I have two tables named as follows:
Products, ProductTypes
var foo = (from products in context.PRODUCTS
join producttype in context.PRODUCTTYPE
group producttype by new {producttype.name, producttype.producttypeid, products.productid} into g
select new
{
ProductName = g.Key.name,
ProductID = g.Key.producttypeid,
NumItems = g.Distinct().Count()
});
Here’s sample data
Product (productId, Name, ProductTypeID)
-------
1 ProductA 1
2 ProductB 1
3 ProductC 2
4 ProductD 3
ProductType (ProductTypeID, Name)
-----------
1 CategoryA
2 CategoryB
3 CategoryC
ProductSubType (ProductSubtypeID, Name, ProductID)
--------------
1 ProductSubType1 1
2 ProductSubType2 1
3 ProductSubType3 2
4 ProductSubType4 2
5 ProductSubType5 2
6 ProductSubType6 2
7 ProductSubType7 3
my results are as follows
CategoryA 1
CategoryA 1
CategoryB 1
CategoryC 1
I’m expecting the results to be
CategoryA 2
CategoryB 1
CategoryC 1
This is correct, except CategoryA should show up as CategoryA 2.
I’m not sure what simple syntax I’m missing here?
Thanks in Advance.
You are currently grouping by a composite key (name, producttypeid, productid) – any unique combination of these will show up as a separate group. It sounds like you want to group by just
producttypeid.Edit:
First of all your LINQ query seems to be missing a part (the join criteria), it should be more like this to even compile:
Your composite key (Name, ProductTypeId, ProductId) defines the unique elements by which your data will be grouped by. Looking at the sample data you provided you can quickly see that there are four unique combinations:
That’s why you have the output you provided:
To get the groups you do want to have, a regular Linq group join would do (names normalized to camel case):
Output:
Let me know if this is what you were after.