C# Dictionary Extension [AddRange]

distancexd

Member
Messages
16
Reaction score
21
Points
18
I love dictionaries in c#. However there is no AddRange method. So I decided to create an extension for it. If you use dictionaries, this can be really helpful for you.

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

How do you use this?
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);

Please, Log in or Register to view URLs content!
 

Harry

Certified Sick ℂunt
Premium Member
Messages
1,253
Reaction score
942
Points
973
Just curious, wouldn't monitoring the amount in the list and using a for method have been more efficient than having dead or not enough stuff stored?
 

distancexd

Member
Messages
16
Reaction score
21
Points
18
Just curious, wouldn't monitoring the amount in the list and using a for method have been more efficient than having dead or not enough stuff stored?
no idea what you mean by this. please explain.
 

VerTical

CEO
Donator
Messages
0
Reaction score
-86
Points
664
I love dictionaries in c#. However there is no AddRange method. So I decided to create an extension for it. If you use dictionaries, this can be really helpful for you.

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

How do you use this?
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);

Please, Log in or Register to view URLs content!
Good thread :blush:
 
Top