在列表C#中使用相同参数连接条目

时间:2012-06-12 12:56:08

标签: c# .net

假设我有以下列表

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

感谢。

1 个答案:

答案 0 :(得分:6)

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

(在你的例子中,你没有乘,你总和)

这将为您提供IEnumerable<Invoice>,您可以在末尾添加.ToList()进行枚举。