联接列表 C# 中具有相同参数的条目

本文关键字:参数 列表 | 更新日期: 2023-09-27 18:36:50

假设我有以下列表

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

将具有相同广告客户 ID 的品牌合并到一个条目中并计算总金额总和的最简单方法是什么?因此,最终列表将如下所示:

List<Invoice> InvoiceList
[0]
   AdvertiserCustomerID = "Generic Brand"
   GrossAmount = 5779
[1]
   AdvertiserCustomerID = "Generic Brand 2"
   GrossAmount = 9211

我通过创建一个新列表并使用 FindIndex 检查广告商客户 ID 来实现这一点,但我想知道是否有更简单的方法可以做到这一点。

谢谢。

联接列表 C# 中具有相同参数的条目

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

(在你的例子中,你不乘法,你求和)

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