Skip to content

Instantly share code, notes, and snippets.

@distantcam
Created November 27, 2013 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save distantcam/7672219 to your computer and use it in GitHub Desktop.
Save distantcam/7672219 to your computer and use it in GitHub Desktop.
Dictionary Extensions
using System;
using System.Linq;
namespace System.Collections.Generic
{
public static class DictionaryExtensions
{
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory)
{
TValue v;
if (dictionary.TryGetValue(key, out v))
{
return v;
}
else
{
v = valueFactory(key);
dictionary.Add(key, v);
return v;
}
}
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
TValue v;
if (dictionary.TryGetValue(key, out v))
{
return v;
}
else
{
dictionary.Add(key, value);
return value;
}
}
public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
{
TValue v;
TValue newValue;
if (dictionary.TryGetValue(key, out v))
{
newValue = updateValueFactory(key, v);
dictionary[key] = newValue;
}
else
{
newValue = addValueFactory(key);
dictionary.Add(key, newValue);
}
return newValue;
}
public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
{
TValue v;
TValue newValue;
if (dictionary.TryGetValue(key, out v))
{
newValue = updateValueFactory(key, v);
dictionary[key] = newValue;
}
else
{
newValue = addValue;
dictionary.Add(key, newValue);
}
return newValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment