You need to create a new KeyValuePair
1 - 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).