2016-08-22 154 views
4

對於LINQ來說相當新穎,並且認爲我想要做的事情應該很容易。我有一個產品列表(ProductId,ProductDesc),我試圖拉取該列表的一個子集,並將其分組到ProductId。從那裏,我想將該子集綁定到listView。這裏是我工作的查詢:LINQ Select and Group By

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和計數,但我需要將描述添加到顯示中。當我進行分組時,我很困惑如何添加產品說明。

+1

'grouping'是現在是由'ProductID'分組的'wowReportData'列表。如果名稱是'wowReportData'的一部分,你可以執行'grouping.First()。Name',但是我不知道你想在'Name'中放置什麼。 –

回答

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並指定如何選擇它


而且,只是一些關於C# - 請看有關命名約定herehere

+1

男士,謝謝,就是這樣。週一愉快! – TrevorGoodchild

+0

@TrevorGoodchild歡迎您:) –

+0

說得過早,沒有獲得設計時間錯誤,但productCounts沒有得到任何東西填充。我是否應該將其轉換爲TopProduct對象列表? – TrevorGoodchild