2

假设我有以下列表

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 来完成此操作,但我想知道是否有更简单的方法来执行此操作。

谢谢。

4

1 回答 1

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

(在您的示例中,您不要相乘,而是求和)

这会给你一个IEnumerable<Invoice>,你可以.ToList()在最后添加一个来枚举。

于 2012-06-12T12:59:34.693 回答