Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a list of a key value pair to dictionary in c#

I want to be able to give a key-value pair list as a parameter in a function, and then add this list to a dictionary, (I also want to control, if the key already exists in the dictionary) how can I do this? Maybe with a for each loop, but Add() function takes 2 arguments.

   public void func(List<KeyValuePair<string, int>> pairs)
    {
        foreach ( var pair in pairs)
        {
            dictionary.Add(pair); // this is not working
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You cannot straight add a KeyValuePair<TKey,TValue> to a dictionary, you need to add as a key and a value:

dictionary.Add(pair.Key, pair.Value);

If you want to overwrite an existing key with a new value, or insert the new key/value (an upsert operation):

dictionary[pair.Key] = pair.Value;

If you only want to add new key/value pairs (do not disturb/overwrite existing data), you can check if the key exists first:

if(!dict.ContainsKey(pair.Key)) dictionary.Add(pair.Key, pair.Value);

Or, if you have it available in your version of .net, you can TryAdd:

dict.TryAdd(pair.Key, pair.Value) //returns false and does not add if the key exists

In either of these latter two (ContainsKey returning true if the items exists, or TryAdd returning false if the item exists) you can use that boolean to decide what to do – merging the data in the dictionary already with the data in the incoming item for example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading