-3

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

Rio Hanz
  • 11
  • 1
  • 2
  • 1
    `countries.Add(someStringValue, someModelItem);` ? – ProgrammingLlama Mar 23 '22 at 04:09
  • 1
    It's hard to recommend a good already-made-post to help you, it's unclear what your actual question is. Right now it just sounds like "how do I add an entry to a dictionary", which is a very fundamental aspect of the dictionary type, so the best I can do is https://stackoverflow.com/questions/1838476/different-ways-of-adding-to-dictionary – gunr2171 Mar 23 '22 at 04:12

1 Answers1

0

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;
Caius Jard
  • 72,509
  • 5
  • 49
  • 80