Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.