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

Leave a Reply

Your email address will not be published. Required fields are marked *


Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://dc.services.visualstudio.com/v2/track` resulted in a `400 Invalid instrumentation key` response: {"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Invalid instrumentation key"}]} in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\P in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113