4

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 the difference if there is between assigning a key=>value pair in a dictionary.

Method1:

results[key] = value;

Method2:

results.Add(key,value);

In method 1, the function Add() was not called but instead the Dictionary named 'results' assigns somehow sets a Key-Value pair by stating code in method1, I assume that it somehow adds the key and value inside the dictionary automatically without Add() being called.

I'm asking this because I'm currently a student and I'm studying C# right now.

Sir/Ma'am, your answers would be of great help and be very much appreciated. Thank you++

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Randel Ramirez
  • 3,671
  • 20
  • 49
  • 63
  • 1
    possible duplicate of [Different ways of adding to Dictionary](http://stackoverflow.com/questions/1838476/different-ways-of-adding-to-dictionary) – Oskar Kjellin Feb 16 '12 at 14:20

2 Answers2

7

The Dictionary<TKey, TValue> indexer's set method (the one that is called when you do results[key] = value;) looks like:

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

The Add method looks like:

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

The only difference being if the third parameter is true, it'll throw an exception if the key already exists.

Side note: A decompiler is the .NET developers second best friend (the first of course being the debugger). This answer came from opening mscorlib in ILSpy.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
5

If the key exists in 1) the value is overwritten. But in 2) it would throw an exception as keys need to be unique

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93