Created
November 6, 2012 10:48
-
-
Save leegould/4023998 to your computer and use it in GitHub Desktop.
Dictionary Extension Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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