C# Count duplicates in List
Hello, I'm having a problem where i need to format a List into a "shopping list" format
Example
shoppingList = {"Item 1", "Item 2", "Item 3", "Item 3", "Item 1", "Item 1", "Item 3", "Item 2"}
Output
Item 1 x 3
Item 2 x 2
Item 3 x 3
Im not sure were to begin, so any help would be appreciated :)
Comment
Best Answer
Answer by Jessespike · Jul 21, 2016 at 08:42 PM
I'm not really satisfied with my answer, seems like it could be done a lot more elegantly. Anyway, this does work:
public string[] shoppingList = new string[]{ "Item 1", "Item 2", "Item 3", "Item 3", "Item 1", "Item 1", "Item 3", "Item 2" };
void OutputEntireShoppingList()
{
Dictionary<string,int> shoppingDictionary = new Dictionary<string, int>();
foreach(string item in shoppingList)
{
if (!shoppingDictionary.ContainsKey(item))
{
shoppingDictionary.Add(item,1);
}
else
{
int count = 0;
shoppingDictionary.TryGetValue(item, out count);
shoppingDictionary.Remove(item);
shoppingDictionary.Add(item, count+1);
}
}
// output the results, each item with quantity
foreach(KeyValuePair<string,int> entry in shoppingDictionary)
{
Debug.Log(entry.Key + " x " + entry.Value);
}
}
Basically create a dictionary that will store the item name and the quantity. Loop through the items in the list, if the item does not exist in the dictionary, then add it. If the item already does exist, then update the value by 1.
Answer by ItsIcear · Jul 22, 2016 at 07:05 AM
Hey, thanks! I was really struggling on how to achieve something like this