假设我有以下列表
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
Run Code Online (Sandbox Code Playgroud)
将具有相同AdvertiserCustomerID的品牌组合到一个条目中的最简单方法是什么,并计算GrossAmount的总和?所以最终的列表看起来像这样:
List<Invoice> InvoiceList
[0]
AdvertiserCustomerID = "Generic Brand"
GrossAmount = 5779
[1]
AdvertiserCustomerID = "Generic Brand 2"
GrossAmount = 9211
Run Code Online (Sandbox Code Playgroud)
我通过创建一个新列表并使用FindIndex检查AdvertiserCustomerID来实现这一点,但我想知道是否有更简单的方法来执行此操作.
谢谢.
var result = InvoiceList
.GroupBy(m => m.AdvertiserCustomerId)
.Select(group => new Invoice {
AdvertiserCustomerID = group.Key,
GrossAmount = group.Sum(g => g.GrossAmount)
}
);
Run Code Online (Sandbox Code Playgroud)
(在你的例子中,你没有乘,你总和)
这会给你一个IEnumerable<Invoice>,你可以.ToList()在最后添加一个枚举.
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |