While trying to add items to a dictionary I discovered that there’s no equivalent of the AddRange which is available for lists.
This is for good reason as adding a KeyValuePair to a dictionary requires first checking that the given key doesn’t already exist and so is more computationally expensive than simply appending to the end of a list.
However, in my case I knew that the items didn’t already exist (and added an option to ignore them if they did).
I also wanted to be able to return a null value form a dictionary if the specified key doesn’t exist, rather than throwing an error when trying to access the value.
To solve both these problems I created the below extension to add the required methods to the Dictionary class.
public static class DictionaryExtensions
{
public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, List<KeyValuePair<TKey, TValue>> itemsToAdd, bool ignoreExisting = true)
{
if (ignoreExisting)
{
itemsToAdd.Where(x => !dictionary.ContainsKey(x.Key)).ToList().ForEach(x => dictionary.Add(x.Key, x.Value));
}
else
{
itemsToAdd.ForEach(x => dictionary.Add(x.Key, x.Value));
}
}
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key) =>
dictionary.TryGetValue(key, out var returnValue) ? returnValue : default;
}
0 Comments