Adding content to a list with specific ID

I have a unique issue so I’ll try to explain the best I can. I have a bunch of cars and each car has colors that a player can buy. I have a SaveData.cs file like this

public struct SaveData {
	public List<CarListData> CarList;

public struct CarListData {
	public int carId;
	public string[] carColors;

I can add cars to the list fine when a player purchases it. It keeps a list of owned cars as the player buys them. It can look like this after purchasing 2 cars…


How can I make the carColors an array of strings and add onto it based on the carID. Here is what I have started with but can’t find any functions to help find based on carID.

public static void purchaseColor(string myCarColor, int selectedCar) {

		var carListData = new CarListData() { carColors = myCarColor };
		saveData.CarList.RemoveAll(t => t.carColors == carListData.carColors);


Player has SaveData struct, which has a list of cars, every car has an ID and array of colors. Array has predefined size so (if it has to be an array) you should inicilize it with number of all colors. carColors = new string[numberOfAllColors]();.

As your CarList is dynamic (we can’t tell that car of ID == 1 will always be in CarList[1]), most obvious solution is just to iterate through CarList and check if carId is equal to selectedCar.

foreach (CarListData entry in CarList)
    if (entry.carId == selectedCar)
        entry.carColors[idOfSpecificColor] = myCarColor;      //Don't know how you want to add that color, but I assume you have some kind of enum for each color or so.. 

Disclaimer :

Naming like CarListData is confusing. It’s a data of just one car, not of the whole list so name should be CarData.

Using Dictionary<int, CarData>(Dictionary) would make things simpler