views:

320

answers:

2

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.

A: 

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

Joel Coehoorn
It could be - but in some situations you may well know that it's not. I can see this being useful sometimes.
Jon Skeet
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
TheSoftwareJedi
+3  A: 

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;
}
Jon Skeet
No clue why I didn't think of this. This is great. Already using it.
TheSoftwareJedi
@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.
Tim Jarvis
@Tim J - I'll accept it eventually. What's your hurry?! Would love more answers, and accepting just discourages that.
TheSoftwareJedi