views:

500

answers:

2

I have System.Collections.Generic.Dictionary<A, B> dict where A and B are classes, and an instance A a (where dict.ContainsKey(a) is true).

Is it possible to get the KeyValuePair containing a directly from the Dictionary?
Or do I need to create a new KeyValuePair: new KeyValuePair<A, B>(a, dict[a])?

+3  A: 

You need to create a new KeyValuePair1 - but bear in mind that KVP is a value type (a struct) anyway, so it's not like you're introducing a new inefficiency by doing this. Any method returning a KVP would be creating a copy anyway - you're just creating the instance directly.

You could always add an extension method to IDictionary<TKey, TValue> if you wanted:

public static KeyValuePair<TKey, TValue> GetEntry
    (this IDictionary<TKey, TValue> dictionary,
     TKey key)
{
    return new KeyValuePair<TKey, TValue>(key, dictionary[key]);
}


1 I was aware that you could iterate over the dictionary entries and find the appropriate entry that way, but I can see no reason why you'd ever want to do so when you've got a perfectly good indexer which is O(1) instead of O(N).

Jon Skeet
My line of thinking was: "It seems I can't get a reference to the actual KeyValuePair object within the dictionary. I wonder why not?". That KeyValuePair is a value type clearly answers that.Thanks Jon
Paul Baker
+1  A: 

As Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, you could use linq:

var pair = _dictionary.SingleOrDefault(p => p.Key == myKey);

Best Regards
Oliver Hanappi

Oliver Hanappi
Well yes, you *could* do that... but it's staggeringly inefficient compared with just fetching the key. (It also assumes that == has been overloaded for the key type, and that the dictionary is using that comparison.) Why would you ever want to do that rather than creating a new KVP directly?
Jon Skeet
its wrong!!! very bad code avoid it!!! consider a dictionary of 9999999 items, u can go to your item directly and create this pair,or go through lots of items and get it...think about it..
Chen Kinnrot