1

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

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

并且我在列表集合中为每个公司提供了多张发票。如何合并集合中的对象、不同的公司并同时添加它们的 InvoiceValues?我想用 Linq 来做!

4

3 回答 3

6

使用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) });
于 2013-05-29T10:13:55.563 回答
2

您可以使用 group by 语句。

List<InvoiceCompany> li = new List<InvoiceCompany>(){
     new InvoiceCompany { Company = "a", InvoiceValue = 1 },
     new InvoiceCompany { Company = "a", InvoiceValue = 2 },
     new InvoiceCompany { Company = "b", InvoiceValue = 1 },
     new InvoiceCompany { Company = "b", InvoiceValue = 2 }
};

var v = from a in li
        group a.InvoiceValue by a.Company into b
        select new { Company = b.Key, Invoices = b.ToList().Sum() };
于 2013-05-29T10:15:14.350 回答
0

尝试按公司对您的 InvoiceValue 进行分组并计算总和:

var v =
from l in list
group l.InvoiceValue by l.Company
into g
select new InvoiceCompany()
{
    Company = g.Key,
    InvoiceValue = g.Sum()
};
于 2013-05-29T10:24:42.103 回答