如何使用字典查找各个键的值

时间:2019-05-19 02:24:13

标签: c# dictionary

字典          字符串[,]单词=新字符串[,]

      /*****Word and Meaning****/

     {{"Absolute","Complete"},                         
     {"Custom","Tradition"},                      
     {"Design","Plan"},                     
     {"New", "Latest"},                       
     {"Sound", "Noise"},                   
     {"Vile", "Base"}};    

/ ****输入用户*** /

     string key = ""; 
     Boolean search=true;
     Console.Write("Input Word: ");
     key= Console.ReadLine();
     Console.WriteLine();    

     for(int ctr=0; ctr < Words.GetLength(0); ctr++)     

/ ****搜索已放入用户的密钥的值是否为真*** /

         if(key == Words[ctr,0])         
            search=true;
             break;          
         else      
             search=false
     if(search==true)

/ ***如何获得第二行单词的价值**** /

         Console.WriteLine(Words: " + key+ "Meaning: " +???;
        else
            Console.WriteLine("Not Found" + key);

请帮助我。.要创建此代码以了解单词的含义:绝对,自定义,设计,新建,声音,邪恶。

1 个答案:

答案 0 :(得分:0)

如果在每个记录的第一位都具有所有取消键,那么这是使用Dictionary的正确时机。

这是实现

  Dictionary<string, string> dict = new Dictionary<string, string>();
  dict.Add("Absolute", "Complete");
  dict.Add("Custom", "Tradition");
  dict.Add("Design", "Plan");
  dict.Add("New", "Latest");
  dict.Add("Sound", "Noise");
  dict.Add("Vile", "Base");

现在您可以从用户那里读取Key的字典

 Console.Write("Input Word: ");
 string key= Console.ReadLine();

现在检查用户输入,例如key是否在词典中可用,例如

if(dict.ContainsKey(key)) //ContainsKey return true if string i.e. key available in dictionary.
    Console.WriteLine("Word is :" + key + "Meaning is" + dict[key]);
else 
    Console.WriteLine("Not Found" + key);