Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a KeyValuePair<> directly from a Dictionary<>

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])?

like image 690
user200783 Avatar asked Oct 24 '09 20:10

user200783


People also ask

What is the difference between KeyValuePair and dictionary C#?

KeyValuePair is the unit of data stored in a Hashtable (or Dictionary ). They are not equivalent to each other. A key value pair contains a single key and a single value. A dictionary or hashtable contains a mapping of many keys to their associated values.

How do you select a key-value pair?

You can use a LINQ expression like so: IList<KeyValuePair<string, int>> values = new List<KeyValuePair<string, int>>(); add your key values. Show activity on this post.

Does a dictionary have an index C#?

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).


2 Answers

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<TKey, TValue>     (this IDictionary<TKey, TValue> dictionary,      TKey key) {     return new KeyValuePair<TKey, TValue>(key, dictionary[key]); } 

As noted in comments, it's entirely possible that the key which is stored in the dictionary is not the same as the one provided, just semantically equal - by some semantics which could be customized by an IEqualityComparer (as with a case-insensitive dictionary, for example.) In that case, the code above would not return the actual entry in the dictionary, but an entry with the key you provided to look up. Unfortunately there's no efficient way of finding the original key - you'd have to iterate over the dictionary :(


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

like image 140
Jon Skeet Avatar answered Oct 14 '22 13:10

Jon Skeet


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

var pair = _dictionary.SingleOrDefault(p => p.Key == myKey); 
like image 25
Oliver Hanappi Avatar answered Oct 14 '22 12:10

Oliver Hanappi