ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IDictionary.GetValue

Better way to read a C# Dictionary

Source

/// <summary>
/// An alternative way to get a value from a dictionary.
/// The return value is a Lazy object containing the value if the value exists in the dictionary.
/// If it doesn't exist, the Lazy object isn't initialized.
/// Therefore, you can use the .IsValueCreated property of Lazy to determine if the object has a value.
/// In addition, if the dictionary did not have the key, .Value property of Lazy will be return the default value of the type.
/// such as null for string and 0 for int.
/// In some cases, simply using the .Value directly of or testing for null may be preferable to testing IsValueCreated
/// </summary>
public static Lazy<TValue> GetValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue retVal;
    if (dictionary.TryGetValue(key, out retVal))
    {
        var retValRef = retVal;
        var lazy = new Lazy<TValue>(() => retValRef);
        retVal = lazy.Value;
        return lazy;
    }

    return new Lazy<TValue>(() => default(TValue));
}

Example

var d = new Dictionary<string, string> {{"KeyApple", "ValueApple"}, {"KeyOrange", "ValueOrange"}, {"KeyPear", "ValuePear"}};

Assert.AreEqual("ValueApple", d.GetValue("KeyApple").Value);
Assert.IsNull(d.GetValue("XXXXXXX").Value);

var lazy1 = d.GetValue("KeyApple");
Assert.IsTrue(lazy1.IsValueCreated);
Assert.AreEqual("ValueApple", lazy1.Value);

var lazy2 = d.GetValue("XXXXXXX");
Assert.IsFalse(lazy2.IsValueCreated);

Author: Kenneth Kasajian

Submitted on: 28 jan. 2015

Language: C#

Type: IDictionary

Views: 6264