How to assign key => value pairs in a dictionary?

Here is my code:

string[] inputs = new[] {"1:2","5:90","7:12","1:70","29:60"}; //Declare Dictionary var results = new Dictionary<int, int>(); //Dictionary<int, int> results = new Dictionary<int, int>(); foreach(string pair in inputs) { string[] split = pair.Split(':'); int key = int.Parse(split[0]); int value = int.Parse(split[1]); //Check for duplicate of the current ID being checked if (results.ContainsKey(key)) { //If the current ID being checked is already in the Dictionary the Qty will be added //Dictionary gets Key=key and the Value=value; A new Key and Value is inserted inside the Dictionary results[key] = results[key] + value; } else { //if No duplicate is found just add the ID and Qty inside the Dictionary results[key] = value; //results.Add(key,value); } } var outputs = new List<string>(); foreach(var kvp in results) { outputs.Add(string.Format("{0}:{1}", kvp.Key, kvp.Value)); } // Turn this back into an array string[] final = outputs.ToArray(); foreach(string s in final) { Console.WriteLine(s); } Console.ReadKey(); 

I want to know if there is a difference between the purpose of the key => value pair in the dictionary.

Method1:

 results[key] = value; 

Method2:

 results.Add(key,value); 

In method 1, the Add () function is not called, but instead, a dictionary named "results" assigns it somehow sets up a key-value pair, indicating the code in method 1, I assume that it somehow adds the key and the value inside the dictionary automatically without calling Add ().

I ask about this because I'm a student now and am learning C # right now.

Sir / Ma'am, your answers will be of great help and will be very grateful. Thanks ++

+4
source share
2 answers

The method for setting the Dictionary<TKey, TValue> (the one that is called when results[key] = value; is executed) looks like this:

 set { this.Insert(key, value, false); } 

The Add method is as follows:

 public void Add(TKey key, TValue value) { this.Insert(key, value, true); } 

The only difference is that if the third parameter is true, it throws an exception if the key already exists.

Side note: the decompiler is the best developer of .NET developers (the first of which, of course, is a debugger). This answer came from the discovery of mscorlib in ILSpy.

+6
source

If the key exists in 1), the value is overwritten. But in 2) this will throw an exception, since the keys must be unique

+5
source

Source: https://habr.com/ru/post/1396845/


All Articles