TrevorGoodchild TrevorGoodchild - 3 months ago 16
C# Question

LINQ Select and Group By

Fairly new to LINQ and think what I'm trying to do should be easy. I have a list of products (

ProductId
,
ProductDesc
) and I'm trying to pull a subset of that list and group it by
ProductId
. From there, I'd like to bind that subset to a listView. Here's the query I'm working on:

productCounts = (from record in wowReportData
group record by record.ProductID
into grouping
orderby grouping.Key
select new topProduct
{
ProductID = grouping.Key,
Quantity = grouping.Count(),
Name = grouping.
}).ToList();


and here's the class I'm trying to populate:

public class topProduct
{
public string ProductID { get; set; }
public int Quantity { get; set; }
public string Name { get; set; }

public topProduct() { }

public topProduct(string productId, string productDesc, int downloadCount)
{
this.ProductID = productId;
this.Name = productDesc;
this.Quantity = downloadCount;
}
}


I had it working fine with just displaying the
productId
and the count but I need to add the description to the display as well. I'm confused as to how to add the product description when I'm doing the grouping.

Answer

I assume that there is only one name for each ProductId so you want to be grouping by 2 fields for that:

productCounts = (from record in wowReportData 
                 group record by new { record.ProductID, record.Name } into grouping
                 orderby grouping.Key.ProductID
                 select new topProduct 
                 { 
                     ProductID = grouping.Key.ProductID, 
                     Quantity = grouping.Count(),
                     Name = grouping.Key.Name
                 }).ToList();

If that is not the case then use FirstOrDefault and specify how to select it


Also, just a bit about C# - please look about naming conventions here and here