2016-12-26 78 views
1

我有一個LINQ查詢一樣跟隨着獲得第一組:LINQ由多個組,然後由價值數

var _transactionsList = TransactionsData 
       .GroupBy(x => new { x.ItemID, x.Title, x.GalleryURL }) 
       .Select(pr => new TransactionsTabResults 
       { 
        ItemID = pr.Key.ItemID, 
        Title = pr.Key.Title, 
        GalleryURL = pr.Key.GalleryURL, 

        ItemPrice = pr.OrderByDescending(a => a.TransactionDate).First().ItemPrice, 

        TotalSoldItems = pr.Count(), 
        TotalRevenuePerItem = pr.Sum(y => y.ItemPrice), 
        AveragePrice = pr.Average(y => y.ItemPrice), 
       }).ToList(); 

我試圖通過分組像這樣獲取的總銷售的物品價值:

ItemID Sales ItemName 

1   1   Item1 
1   3   Item1 
1   5   Item1 
1   6   Item1 
2   2   Item2 
2   2   Item2 
2   2   Item2 
2   2   Item2 

所需的輸出將是:

ItemID Sales ItemName 
1   15  Item1 
2   8  Item2 

上面我寫的查詢給了我錯誤的值總銷量說:

TotalSoldItems = pr.Count(), 

我怎麼能算,或者和它有唯一的ID一個項目的所有銷售(這是我通過編組)...

我在做什麼錯? ?

回答

0

您正在使用GroubBy錯誤的方式。每次創建新的獨特對象。所以,你的.GroupBy(x => new { x.ItemID, x.Title, x.GalleryURL }).Select(x => new { Key = new { x.ItemID, x.Title, x.GalleryURL}, Value =x })意味着同樣的

如果你需要那麼唯一的ID組憑身份證只能

TransactionsData 
.GroupBy(x => x.ItemID) 
.Select(pr => new TransactionsTabResults 
{ 
    ItemID = pr.Key, 
    Title = pr.First().Title, 
    GalleryURL = pr.First().GalleryURL, 
    ItemPrice = pr.OrderByDescending(a => a.TransactionDate).First().ItemPrice, 
    TotalSoldItems = pr.Count(), 
    TotalRevenuePerItem = pr.Sum(y => y.ItemPrice), 
    AveragePrice = pr.Average(y => y.ItemPrice), 
}).ToList(); 

諮詢

優化LINQ。您正在遍歷集合很多次。這是建議的代碼:

TransactionsData 
.GroupBy(x => x.ItemID) 
.Select(pr => 
{ 
    var items = x.pr.ToArray; 
    var sum = items.Sum(y => y.ItemPrice); 
    return new TransactionsTabResults 
    { 
     ItemID = pr.Key, 
     Title = items[0].Title, 
     GalleryURL = items[0].GalleryURL, 
     ItemPrice = pr.Aggregate((max, cur)=>max.TransactionDate<cur.TransactionDate?cur:max).ItemPrice, 
     TotalSoldItems = items.Length, 
     TotalRevenuePerItem = sum, 
     AveragePrice = sum/items.Length, 
    }; 
}).ToList();