2010-03-25

Merge (fka Upsert) Extension Method for IDictionary

[TestFixture]
public class IDictionaryExtensionsTests
{
    [Test]
    public void ShouldAddIfKeyDoesNotExists()
    {
        var dictionary = new Dictionary<string, int> { { "nøgle", 100 }, { "key", 200 } };

        dictionary.Merge("nyckel", 300).Count.Should().Be.EqualTo(3);
    }

    [Test]
    public void ShouldUpdateIfKeyExists()
    {
        var dictionary = new Dictionary<string, int> { { "nøgle", 100 }, { "key", 200 } };

        dictionary.Merge("nøgle", 400).Count.Should().Be.EqualTo(2);
        dictionary["nøgle"].Should().Be.EqualTo(400);
    }
}

/// <summary>
/// Adds the key/value pair if the key doesn't exist, or updates the key with
/// the supplied value if the key exists.
/// <remarks>
/// The name "Merge" is taken from SQL:2003 (f.k.a. "Upsert")
/// <see cref="en.wikipedia.org/wiki/Merge_(SQL)"/>
/// </remarks>
/// </summary>
public static class IDictionaryExtensions
{
    public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> thiz, TKey key, TValue value)
    {
        if (thiz.ContainsKey(key))
        {
            thiz.Remove(key);
        }

        thiz.Add(key, value);

        return thiz;
    }
}