2012-06-12 59 views
2

比方說,我有以下列表在列表C#相同的參數加入條目

List<Invoice> InvoiceList 

[0] 
    AdvertiserCustomerID = "Generic Brand" 
    GrossAmount = 1452 
[1] 
    AdvertiserCustomerID = "Generic Brand" 
    GrossAmount = 4325 
[2] 
    AdvertiserCustomerID = "Generic Brand" 
    GrossAmount = 2 
[3] 
    AdvertiserCustomerID = "Generic Brand 2" 
    GrossAmount = 9211 

什麼是與同AdvertiserCustomerID品牌組合成一個條目的最簡單的方法,並計算的總和GrossAmount?所以最終名單應該是這樣的:

List<Invoice> InvoiceList 

[0] 
    AdvertiserCustomerID = "Generic Brand" 
    GrossAmount = 5779 
[1] 
    AdvertiserCustomerID = "Generic Brand 2" 
    GrossAmount = 9211 

我通過創建一個新的列表,並與FindIndex朝AdvertiserCustomerID檢查做到了這一點,但我不知道是否有這樣做的一個簡單的方法。

謝謝。

回答

6
var result = InvoiceList 
    .GroupBy(m => m.AdvertiserCustomerId) 
    .Select(group => new Invoice { 
       AdvertiserCustomerID = group.Key, 
       GrossAmount = group.Sum(g => g.GrossAmount) 
       } 
    ); 

(在你的榜樣,你不乘,你總和)

這會給你一個IEnumerable<Invoice>,你可以在最後枚舉添加.ToList()

相關問題