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

Time:03-20

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
        }
    }

CodePudding user response:

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

CodePudding user response:

The Dictionary does not have AddRange method, so you can't eliminate the loop from your code.

As for KeyValuePair, then, again, the Dictionary does not have ready-to-use overload for this, but you have at least the following options

  1. Use Add method with manual decomposition: dictionary.Add(pair.Key, pair.Value);

  2. Create extension method that will handle KeyValuePairs

     public static class Extensions
     {
         public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dict,
                                              KeyValuePair<TKey, TValue> value)
         {
             dict.Add(value.Key, value.Value);
         }
     }
    

    Usage: dictionary.Add(pair);

To handle "key already exists" case, you can use dictionary.ContainsKey or just catching exception throwed by Add method (choose what fit best depending on the frequency of duplicated cases and you control flow)

CodePudding user response:

You need to deconstruct the KeyValuePair down and add it from there.

void func(Dictionary<string,int> dictionary, List<KeyValuePair<string, int>> pairs)
{
    foreach (var (key, value) in pairs)
    {
        dictionary.Add(key,value);
    }
}
  • Related