ThinkGeek - Cool Stuff for Geeks and Technophiles

Are you tired of doing the if(dict.Contains(key))… pattern? Extend Dictionary:

public static R ValueOrSomethingElse<K, V, R>(this Dictionary<K, V> Col, K Key, Func<V, R> Transform, Func<R> SomethingElse)
{
   if (Col.ContainsKey(Key))
      return Transform(Col[Key]);
   else
      return SomethingElse();
}

Example usage:

Dictionary<string, DateTime> BDays = new Dictionary<string, DateTime>();
...
BDays.ValueOrSomethingElse("Mark", d => d.ToString("MM/dd/yy"), () => "Unknown BirthDate");

The second parameter is a lambda for transforming the value if the key is found. The third parameter is a lambda to execute and return if the key is not found. I have the third parameter(something else) as a lambda in case the “something else” is an expensive operation.

One Response to “C#: .NET Generic Dictionary Improvement”

  1. This should be even faster:
    {
    V Value;
    if (Col.TryGetValue(Key, out Value))
    {
    return Transform(Value);
    }
    else
    {
    return SomethingElse();
    }
    }

    Also, typical C# style is to lower-case parameters and member variables, so I would think Key->key, Value->value, Col->col, but that’s a matter of style.