Skip to main content
 首页 » 编程设计

c#之使用 linq 合并集合

2024年01月22日29jpfss

我有一组具有重复值的对象。假设对象是:

public InvoiceCompany 
{ 
    public decimal InvoiceValue { get; set; } 
    public string Company { get; set; } 
} 

我在 List 集合中为每个公司都有多张发票。如何合并集合中的对象、不同的公司并同时添加它们的 InvoiceValues?我想使用 Linq 来完成!

请您参考如下方法:

使用GroupBy:

var list = new List<InvoiceCompany>(); //your collection of invoices 
var grouped = list.GroupBy(x => x.Company) 
                  .Select(g => new InvoiceCompany { Company = g.Key, InvoiceValue = g.Sum(x => x.InvoiceValue) });