How to get quantity of same item in list?

How could I get quantity of same item in list? Lets say I have a treasureBag list, which contains Treasure class variables, and inside there’s 3 sapphires, 1 ruby, and 1 emerald. How could I possibly return specific integer for their amount?

Ok I read your comments in the other answer and it looks like you have a unique id for each item. If this unique id starts at 0 you can hold an array of counts with as index the id of the item and as value the count of that item.

To initialize this you just start with an integer array with size equal to the number of items there are and all values set to 0. Then you iterate over all your items, use the unique id as index to access the count in the array, and increase that number with one.

Pretty simple and if you don’t have a unique id starting from zero, you can apply the same principle with a dictionary that maps integers to integers.

The advantages of this method is that you only have to iterate once over the entire list to get ALL the counts. Also you never need to adjust your function when you add a new item type. (With a switch statement you would.)

If the Treasure class has a variable type with type of enum TreasureType { Sapphire, Ruby, Emerald } then:

int sapphireCount, rubyCount, emeraldCount;

foreach(Treasure item in treasureBag){
  switch(item.type){
    case TreasureType.Sapphire:
      sapphireCount++;
      break;
    case TreasureType.Ruby:
      rubyCount++;
      break;
    case TreasureType.Emerald:
      emeraldCount++;
      break;
  }
}