This is my code
Dictionary
d.Add("Xyz", 1234567890);
d.Add("ABC", 123456780);
d.Add("DEF", 9999999999);
if (d.ContainsValue(no))
{
Here i would like to get the name of the corresponding number
}
In this i will get the no from the user text box where i should i compare that no with the dictionary available ad has to produce the name if the pair exists.
Any idea please i am using 2.0 Framework
Dorababu MekaPosted Aug 22, 2011, 11:13 AM
long l=0;
if (d.ContainsValue(no))
{
foreach (KeyValuePair
{
l = item.Value;
if (l == no)
{
label1.Text = item.Key;
}
}
}
Andrew FensterPosted Aug 22, 2011, 11:17 AM
A Dictionary has a set keys, each of which is unique. Each key has a value. You pass in a key, and the Dictionary gives you the value. You're trying to pass in a value and get a key. The problem with this is that the same value can have multiple keys.
Here's your code, slightly modified:
Dictionary
d.Add("ABC", 1);
d.Add("DEF", 1);
d.Add("XYZ", 2);
Now if someone wants to know the value for ABC, the answer is easy: 1. However if someone wants to go the other way and get the key for 1, the answer is EITHER ABC OR DEF. So you have a problem trying to go from the value backward to the key. You can end up with more than one key.
If the numbers in your problem are unique, then the easiest thing is to just switch around your dictionary:
Dictionary
d.Add(9963741473, "ABC");
d.Add(8886746777, "DEF");
d.Add(9030144435, "XYZ");
if(d.ContainsKey(no)
return d[no];
Let me know if you have problems.