Wednesday, April 6, 2011

Is there an IDictionary implementation that returns null on missing key instead of throwing?

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return default(T)?

I know about the "TryGetValue" method, but that's impossible to use with linq.

Would this efficiently do what I need?:

myDict.FirstOrDefault(a => a.Key == someKeyKalue);

I don't think it will as I think it will iterate the keys instead of using a Hash lookup.

From stackoverflow
  • No, because otherwise how would you know the difference when the key exists but stored a null value? That could be significant.

    Jon Skeet : It could be - but in some situations you may well know that it's not. I can see this being useful sometimes.
    TheSoftwareJedi : If you know null isn't in there - this is extremely nice to have. It makes joining these things in Linq (which is all I do lately) so much easier
  • Indeed, that won't be efficient at all.

    You could always write an extension method:

    public static TValue GetValueOrDefault<TKey,TValue>
        (this IDictionary<TKey, TValue> dictionary, TKey key)
    {
        TValue ret;
        // Ignore return value
        dictionary.TryGetValue(key, out ret);
        return ret;
    }
    
    TheSoftwareJedi : No clue why I didn't think of this. This is great. Already using it.
    Tim Jarvis : @TheSoftwareJedi, If this is your accepted answer, perhaps you could mark it as such, Its very helpfull for people to see accepted answers at a glance. It will also pin this answer to the top.
    TheSoftwareJedi : @Tim J - I'll accept it eventually. What's your hurry?! Would love more answers, and accepting just discourages that.

0 comments:

Post a Comment