我想检查列表中的重复值并将价格汇总在一起。
请遵循以下示例。
例如。
var list = new List<Item>();
list.Add(new Item() { code= "521523", text= "cookie", price= 5});
list.Add(new Item() { code= "521523", text= "donut", price= 20 });
list.Add(new Item() { code= "521524", text= "coffee", price= 15 });
list.Add(new Item() { code= "521524", text= "water", price= 16 });
list.Add(new Item() { code= "521525", text= "other", price= 16 });
结果
code= "521523", text= "cookie", price= 25
code= "521524", text= "coffee", price= 31
code= "521525", text= "other", price= 16
答案 0 :(得分:2)
您可以使用GroupBy
:
list = list
.GroupBy(i => i.code)
.Select(g => new Item
{
code = g.Key,
text = String.Join(",", g.Select(i => i.text)), // join better than taking First()
price = g.Sum(i => i.price)
})
.ToList();