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 ++
source share