Combine duplicates from an ArrayList
-
For some reason I can't figure this out Let's say I have an ArrayList of a class that has a string productName and an int called count. I want to basically combine the duplicates in the following way.
productName | count ------------------- Product1 | 1 Product2 | 1 Product1 | 1 After combining I'd want it to look like productName | count ------------------- Product1 | 2 Product2 | 1 What is my best bet?
-
For some reason I can't figure this out Let's say I have an ArrayList of a class that has a string productName and an int called count. I want to basically combine the duplicates in the following way.
productName | count ------------------- Product1 | 1 Product2 | 1 Product1 | 1 After combining I'd want it to look like productName | count ------------------- Product1 | 2 Product2 | 1 What is my best bet?
Hello, Let me suggest a redesign. Instead of ArrayList you could use a Hashtable (or Dictonary .Net>1.1). Your "Value" would be the full instance of the class, and the "Key" would be the productName. You could than make an "Add" Method which controls if the Key already exist. If no -> add the instance to the Collection. If yes -> increase the count of the existing instance. Hope it helps! All the best, Martin