Skip to content

Instantly share code, notes, and snippets.

@leegould
Created November 6, 2012 10:48
Show Gist options
  • Save leegould/4023998 to your computer and use it in GitHub Desktop.
Save leegould/4023998 to your computer and use it in GitHub Desktop.
Dictionary Extension Methods
public static class DictionaryExtensions
{
/// <summary>
/// Add a range of items to a dictionary.
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <typeparam name="TU">type</typeparam>
/// <param name="source">the dictionary</param>
/// <param name="dictionary">the range to be added</param>
public static void AddRange<T, TU>(this IDictionary<T, TU> source, IDictionary<T, TU> dictionary)
{
foreach (var kvp in dictionary)
{
if (source.ContainsKey(kvp.Key))
{
throw new ArgumentException("An item with the same key has already been added.");
}
source.Add(kvp);
}
}
/// <summary>
/// Add a range of values to a dictionary object. The item will only be added if it is not already in the collection.
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <typeparam name="TU">type</typeparam>
/// <param name="source">the dictionary</param>
/// <param name="dictionary">the range to be added</param>
public static void AddDistinctRange<T, TU>(this IDictionary<T, TU> source, IDictionary<T, TU> dictionary)
{
foreach (var kvp in dictionary)
{
if (!source.ContainsKey(kvp.Key))
{
source.Add(kvp);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment