-3

I want to check the duplicate values in the list and bring the prices together.

Follow the example below.

ex.

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 });

result

code= "521523", text= "cookie", price= 25
code= "521524", text= "coffee", price= 31
code= "521525", text= "other", price= 16
babyPG
  • 15
  • 2
  • 2
    Probably your problem similar like these issues: https://stackoverflow.com/questions/23805792/list-distinct-entries-based-on-property-and-sum-of-duplicates, https://stackoverflow.com/questions/27456281/how-to-aggregate-duplicate-records-and-sum-value-using-c-sharp & https://stackoverflow.com/questions/50449204/linq-remove-duplicates-and-result-item-to-have-sum-of-quantities. – Tetsuya Yamamoto Nov 16 '18 at 08:45
  • 3
    So, do you have any problem doing that? – SᴇM Nov 16 '18 at 08:46
  • 1
    in addition to what the others said: What exacly is your Question? please have a look at [how-to-ask](http://stackoverflow.com/help/how-to-ask) – swe Nov 16 '18 at 08:48
  • 1
    Why is "521524" "coffee" and not "water"? – Hans Kesting Nov 16 '18 at 09:24

1 Answers1

2

You can use 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();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939