Linq Grouping Question
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.PRODUCTTYP开发者_运维问答E
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:
var results = (from products in Products
join productType in ProductTypes
on products.ProductTypeID equals productType.ProductTypeId
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()
}).ToList();
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:
(Name, ProductTypeId, ProductId)
(CategoryA, 1, 1)
(CategoryA, 2, 1)
(CategoryB, 3, 2)
(CategoryC, 4, 3)
That's why you have the output you provided:
(Name, ProductId)
CategoryA 1
CategoryA 1
CategoryB 1
CategoryC 1
To get the groups you do want to have, a regular Linq group join would do (names normalized to camel case):
var ProductTypeList = (from productType in ProductTypes
join product in Products
on productType.ProductTypeId equals product.ProductTypeID into prod
select new
{
ProductTypeId = productType.ProductTypeId,
Name = productType.Name,
Products = prod.ToList(),
NumItems = prod.Count()
}).ToList();
foreach (var item in ProductTypeList)
{
Console.WriteLine("{0} : {1}", item.Name, item.NumItems);
}
Output:
CategoryA : 2
CategoryB : 1
CategoryC : 1
Let me know if this is what you were after.
精彩评论