I'm converting a back-end to c# and I noticed a weird behavior
when I add an element to a list in a dictionary
(inside another dictionary actually):
shortly it adds the value to EVERY list in EVERY element in the dictionary.
Here's the code:
public class Validator_Counter_Model
{
public readonly Dictionary<string,Info_Model> Info;
private Dictionary<string,Dictionary<DateTime,List<int>>> _map = new Dictionary<string, Dictionary<DateTime,List<int>>>();
public Validator_Counter_Model(Dictionary<string, Info_Model> info)
{
Info = info;
}
public void Add(Validation_Element element)
{
/// #### PROBLEM IS HERE!
if (!_map.ContainsKey(element.Id))
{
Dictionary<DateTime, List<int>> newmap = new Dictionary<DateTime, List<int>>();
_map.Add(element.Id, newmap);
}
DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
if (!_map[element.Id].ContainsKey(fulldate.Date))
{
List<int> newList = new List<int>();
_map[element.Id].Add(fulldate.Date, newList);
}
_map[element.Id][fulldate.Date].Add(element.Time);
/// #### PROBLEM IS HERE!
}
public void Del(Validation_Element element)
{
DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
DateTime date = new DateTime(fulldate.Year, fulldate.Month, fulldate.Day);
_map[element.Id][date].Remove(element.Time);
}
public void Update(Dictionary<string, Dictionary<DateTime, List<int>>> newMap) => _map = newMap;
public Dictionary<string, Dictionary<DateTime, List<int>>> map => _map;
}
}