Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
what i want to do is .. if perticular key matches with my string then i want to display that dictionaries value ..
Posted

You don't need to loop though the dictionary.
You can just check if the dictionary key contains that key value,
If it does, then access it directly.

For e.g.
if (myDict.Contains(strng))
{
   Console.WriteLine(myDict[strng]);
}
else
{
   Console.WriteLine("Not Found");
}
 
Share this answer
 
v2
no need for foreach loop do it like this
C#
 Dictionary<string,string> dic = new Dictionary<string,string>();
   dic.Add("1", "abc");
   dic.Add("2", "bcd");
   dic.Add("3", "nadeem");
   string dicvalue = "";
   if (dic.ContainsKey("3"))
     {
       dic.TryGetValue("3", out dicvalue); // initialize the dicvalue with the corresponding key vlaue
     }
else
{
  // value not exist
}
// value of the key is stored in dicvalue   variable
//display the dicvalue  variable  value
 
Share this answer
 
v2
Zafar is almost right. This is better:
C#
Dictionary<string,string> dic = new Dictionary<string,string>();
dic.Add("1", "abc");
dic.Add("2", "bcd");
dic.Add("3", "nadeem");
string dicvalue = "";
if (!dic.TryGetValue("3", out dicvalue))  // get the value for key "3" into dicvalue if it is there, return false if not there
{
  // value not exist
}
// value of the key is stored in dicvalue   variable
//display the dicvalue  variable  value
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900