Reputation: 599
I google'd around for this for a good twenty minutes. Forgive me if this is a duplicate.
So I am reading from a app.config file and have a bunch of keys/value pairs
{'a','1'},{'b','5'},{'c','9'} ... etc
Finding the values when give the keys are easy. But going reverse proves to be much more difficult than I thought it would.
Strangely the api on msdn does not seem to mention anything about reverse search.
How would you find the value of the key if you were only given "1" if you are allowed to at all?
Upvotes: 1
Views: 2947
Reputation: 16324
The nicest way I can think to do it is to use Linq on the AllKeys
property:
myNameValueCollection.AllKeys.First(key => myNameValueCollection[key] == myValue);
It is unfortunate that NameValueCollection
does not implement IEnumerable<KeyValuePair<string, string>>
.
I see from your comments that you're not very familiar with Linq. I've provided some links in the comments to get you going. This particular Linq query is approximately equivalent to the following, written very tersely:
foreach(var key in myNameValueCollection.AllKeys)
{
var value = myNameValueCollection.AllKeys[key];
if (value == myValue)
{
return value;
}
}
Upvotes: 5
Reputation: 48114
Of course this is a one way street because the hashing function is applied to the key and not the value. However there are obvious work arounds if you're values are distinct (keep in mind they don't have to be). Eugen's suggestion in the comments is probably the best if you're going to repeatedly do look ups by the values. If you're looking for more of a one off solution you can just loop over the keys checking for a match on the value. When the value matches you know what key it's associated with.
Upvotes: 1