Skip to content

Instantly share code, notes, and snippets.

@dsherret
Last active May 31, 2017 20:34
Show Gist options
  • Save dsherret/91dc4b26175d5dfd4f8e to your computer and use it in GitHub Desktop.
Save dsherret/91dc4b26175d5dfd4f8e to your computer and use it in GitHub Desktop.
Dictionary - AddIfNotExists Extension Method
/// <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