Last active
May 31, 2017 20:34
-
-
Save dsherret/91dc4b26175d5dfd4f8e to your computer and use it in GitHub Desktop.
Dictionary - AddIfNotExists Extension Method
This file contains 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
/// <summary> | |
/// Very simple extension method for adding an item to a dictionary | |
/// and not evaluating the function unless the key doesn't exist. | |
/// | |
/// Example with Entity Framework: | |
/// dataValueCache.AddIfNotExists(dataID, () => db.DataItems.First(d => d.DataID == dataID).Value); | |
/// </summary> | |
/// <param name="key">The dictionary key.</param> | |
/// <param name="value">The dictionary value.</param> | |
/// <returns>If the item was added to the dictionary.</returns> | |
static public bool AddIfNotExists<T, U>(this Dictionary<T, U> source, T key, Func<U> value) | |
{ | |
if (!source.ContainsKey(key)) | |
{ | |
source.Add(key, value()); | |
return true; | |
} | |
else | |
{ | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment