What's new

.NET [Extension] Dictionary AddRange

  • Thread starter distancexd
  • Start date
  • Views 1,217
distancexd

distancexd

officially the coolest kid you'll never meet
Messages
13
Reaction score
14
Points
30
Sin$
7
I love dictionaries in c#. However there is no AddRange method. So I decided to create an extension for it.

Make sure this code is in a static class as it's an extension.
Code:
public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<TKey, TValue>> objects)
{
     foreach (var obj in objects)
     {
          if (dictionary.ContainsKey(obj.Key))
               dictionary[obj.Key] = obj.Value;
          else
               dictionary.Add(obj.Key, obj.Value);
     }
}

Example usage:
Code:
var dictionary = new Dictionary<string, string>();
var list = new List<KeyValuePair<string, string>>()
{
     new KeyValuePair<string, string>("key", "value"),
     new KeyValuePair<string, string>("key1", "value"),
     new KeyValuePair<string, string>("key2", "value"),
     new KeyValuePair<string, string>("key3", "value"),
     new KeyValuePair<string, string>("key4", "value"),
     new KeyValuePair<string, string>("key5", "value")
};
dictionary.AddRange(list);

View Gist
 
Top Bottom
Login
Register