我有一组具有重复值的对象。让我们说对象是:
public InvoiceCompany
{
public decimal InvoiceValue { get; set; }
public string Company { get; set; }
}
我在List集合中为每个公司分配了多张发票。如何合并集合中的对象,不同的公司并同时添加其InvoiceValues?我想用Linq做到这一点!
答案 0 :(得分: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) });
答案 1 :(得分:2)
您可以使用分组声明。
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() };
答案 2 :(得分: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()
};