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