2

Is there a way to write this more compact ?

return _searchRedirectionMap.ContainsKey(query) ? _searchRedirectionMap[query] : "";

Givent that _searchRedirectionMap is defined as a IDictionary<string,string>

Roman
  • 7,933
  • 17
  • 56
  • 72

2 Answers2

6

You could write an extension method on IDictionary that utilizes the TryGetValue method:

public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue)
{
    TValue outValue;
    if (source.TryGetValue(key, outValue))
    {
        return outValue;
    }

    return defaultValue;
}

and then you could use it like this:

return _searchRedirectionMap.GetValueOrDefault(query, string.Empty);
Richard
  • 8,110
  • 3
  • 36
  • 59
  • Its really a shame something like this isnt defined in ``IDictionary``, as this would make some if-else-constructs obsolete. Which in turn makes the code more readable in most cases... – Philip Daubmeier Jul 08 '12 at 12:52
  • 1
    Well this is a bit specific (off the top of my head, I can't think of a bit of code in my projects that would use a default value if it wasn't in the dictionary; usually if it's not there I need to do something completely different) and has its performance drawbacks as `defaultValue` must be obtained/executed/resolved and passed into the method even if the dictionary does actually contain the key. But that's what extension methods are for: if you need that kind of method because you use it a lot? No problem! I just think it's debatable that it should be in the BCL. – Chris Sinclair Jul 08 '12 at 12:57
  • @ChrisSinclair Actually, a pattern that is fairly useful is a dictionary that inserts a default value for a missing key when it's first accessed, which avoids the default being recreated more often than necessary. (E.g. to do a frequency count.) Not sure if there's a case to be made for this to be in the BCL, but for the sake of a sane API you'd want a separate class for this instead of an extension. – millimoose Jul 08 '12 at 13:22
  • @millimoose: I can see that as viable, perhaps if you provide a fixed value as part of the constructor. But a method that _gets_ a value _or_ a default value (without inserting that value into that key) and then use it frequently in the consuming code seems a bit too context-specific to me. – Chris Sinclair Jul 08 '12 at 14:12
0

You can use TryGetValue method but it will return null for string type:

_searchRedirectionMap.TryGetValue(key, out value);

Documentation: MSDN

Adam
  • 26,549
  • 8
  • 62
  • 79