KeyNotFoundException: The given key was not present in the dictionary.

I wrote surely like,

b.WeeklySalesBS[gameWeekRecord] = b.DailySalesBS[gameWeekRecord * 7 - 6]+....;

Then, isn’t this same effect with b.WeeklySalesBS.Add(gameWeekRecord, …); ?

Why KeyNotFoundException this error occur? and how to fix?

Thanks.

No.

“b.WeeklySalesBS.Add(gameWeekRecord, …);” will create a New item in the dictionary with the Key gameWeekRecord.

"b.WeeklySalesBS[gameWeekRecord] = " will look for an Existing item in the dictionary with the Key of gameWeekRecord and then assign it a new value.

You don’t have an item with key gameWeekRecord, you need to add it before you use it.

Actually, this is (sadly) not the case
This works perfectly fine:

	Dictionary<string, int> dict;
	void Start () {
		dict = new Dictionary<string, int>();
		dict["test"] = 3;
		print( dict["test"] );
	}

However this doesn’t

	Dictionary<string, int> dict;
	void Start () {
		dict = new Dictionary<string, int>();
		dict["test"] = dict["other"];
		print( dict["test"] );
	}

Im also not entirely sure what his intentions are
b.WeeklySalesBS[gameWeekRecord] = b.DailySalesBS[gameWeekRecord * 7 - 6]
is effectively
dict[5] = dict[5*7-6]
can you guarantee that the second key, with a much larger value, exists already? if its really a counter of weeks, and you have only passed 10 weeks, this is looking for the entry for week 64, which hasnt happened yet.

tl;dr: exactly as the error says, b.DailySalesBS[gameWeekRecord * 7 - 6] does not exist

Thx I solved with check with .ContainsKey and if not, assign 0 value.

yes I intended get weekly sales (seven day’s daily sale’s sum) and store those datas.

Oh. That is not what I expected at all.