Roman
Roman

Reputation: 8231

Compact dictionary key lookup

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>

Upvotes: 2

Views: 354

Answers (2)

Adam
Adam

Reputation: 26917

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

_searchRedirectionMap.TryGetValue(key, out value);

Documentation: MSDN

Upvotes: 0

Richard
Richard

Reputation: 8280

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);

Upvotes: 6

Related Questions