对LINQ来说相当新,并且想想我应该做的事应该很容易。我有一个产品列表(ProductId
,ProductDesc
),我试图提取该列表的一个子集并按ProductId
对其进行分组。从那里,我想将该子集绑定到listView。以下是我正在处理的查询:
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();
这是我尝试填充的课程:
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;
}
}
我只需显示productId
和计数就可以正常工作,但我还需要将说明添加到显示中。在我进行分组时,我对如何添加产品说明感到困惑。
答案 0 :(得分:4)
我假设每个ProductId
只有一个名称,因此您希望按2个字段进行分组:
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();
如果不是这种情况,请使用FirstOrDefault
并指定如何选择
答案 1 :(得分:0)
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.Sum(t=>t.Quantity),
Name = grouping.Key.Name
}).ToList();
总金额应为按以下方式计算的数量