Search code examples
c#dictionary

How to add multiple values to Dictionary in C#?


What is the best way to add multiple values to a Dictionary if I don't want to call ".Add()" multiple times.

Edit: I want to fill it after initiation! there are already some values in the Dictionary!

So instead of

    myDictionary.Add("a", "b");
    myDictionary.Add("f", "v");
    myDictionary.Add("s", "d");
    myDictionary.Add("r", "m");
    ...

I want to do something like this

 myDictionary.Add(["a","b"], ["f","v"],["s","d"]);

Is there a way to do so?


Solution

  • You can use curly braces for that, though this only works for initialization:

    var myDictionary = new Dictionary<string, string>
    {
        {"a", "b"},
        {"f", "v"},
        {"s", "d"},
        {"r", "m"}
    };
    

    This is called "collection initialization" and works for any ICollection<T> (see link for dictionaries or this link for any other collection type). In fact, it works for any object type that implements IEnumerable and contains an Add method:

    class Foo : IEnumerable
    {
        public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
        // ...
    }
    
    Foo foo = new Foo
    {
        {1, 2, 3},
        {2, 3, 4}
    };
    

    Basically this is just syntactic sugar for calling the Add-method repeatedly. After initialization there are a few ways to do this, one of them being calling the Add-methods manually:

    var myDictionary = new Dictionary<string, string>
        {
            {"a", "b"},
            {"f", "v"}
        };
    
    var anotherDictionary = new Dictionary<string, string>
        {
            {"s", "d"},
            {"r", "m"}
        };
    
    // Merge anotherDictionary into myDictionary, which may throw
    // (as usually) on duplicate keys
    foreach (var keyValuePair in anotherDictionary)
    {
        myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
    }
    

    Or as extension method:

    static class DictionaryExtensions
    {
        public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (target == null) throw new ArgumentNullException("target");
    
            foreach (var keyValuePair in source)
            {
                target.Add(keyValuePair.Key, keyValuePair.Value);
            }
        }
    }
    
    var myDictionary = new Dictionary<string, string>
        {
            {"a", "b"},
            {"f", "v"}
        };
    
    myDictionary.Add(new Dictionary<string, string>
        {
            {"s", "d"},
            {"r", "m"}
        });