foreach string in strings, increment a value

I have a box (boxSize), each box has an array of items represented as strings(boxContents).
I want to count the occurrence of each item in the array.

For instance, if the box can hold 6 things, and 2 of them are red, i want to know there are 2 red things.

Right now i am trying to use this function to count under update. I know it’s wrong, and i am not sure how to get what’s right.

void countColors () {
		foreach (string Red in boxContents) {
			colorCount[0] = colorCount[0] + 1;
			Debug.Log("There are this many red's in the box: " + colorCount[0]);
			}
		}

Any help appreciated.

Do you want something like:

int count = 0;
void countColors () 
{
    foreach (string stringToSearch in boxContents) 
    {
        if(stringToSearch == "Red")
            count++;
    }
    Debug.Log("There are this many red's in the box: " + count);
}

the “stringToSearch” variable is the name of a temporary variable that gets used in your foreach loop. stringToSearch is a different string every time it iterates through the loop. on each loop, it is assigned to the next value stored in the array or list called boxContents.

I’d use the dictionary generic collection type for this. (Include a using System.Collections.Generic; statement)

var result = new Dictionary<string, int>();
foreach (var item in boxContents) {
   if (!result.ContainsKey(item))
      result[item] = 0; // not sure if this part is nessisary
   result[item]++;
}
Debug.Log(result["Red"]);