How to Add Data in Dictionary C# with parameter from Model /Object Example : Dictionary<string, ModelItem> countries = new Dictionary<string, ModelItem>();
Code Sample, How to Add Data in Dictionary C# with parameter from Model /Object
How to Add Data in Dictionary C# with parameter from Model /Object Example : Dictionary<string, ModelItem> countries = new Dictionary<string, ModelItem>();
Code Sample, How to Add Data in Dictionary C# with parameter from Model /Object
To add in a way that will crash if there is a same key already exists in the dictionary:
countries.Add("USA", someModel);
To add in a way that will overwrite the existing Value with your new one if a same key already exists in the dictionary:
countries["USA"] = someModel;
To add in a way that will stop and not add if the same key already exists in the dictionary:
bool didAdd = countries.TryAdd("USA, someModel);
Or if your .net is old and doesn't have TryAdd:
if(!countries.ContainsKey("USA")) countries["USA"] = someModel;
You can use the bool returned from ContainsKey/TryAdd to decide what to do if the dictionary already contains the object. Perhaps you want to update only some of it:
//update or add
if(countries.ContainsKey("USA"))
countries["USA"].Name = someModel.Name;
else
countries["USA"] = someModel;