如何在foreach循环中迭代Dictionary键值 [英] How to iterate through Dictionary key value in foreach loop

查看:69
本文介绍了如何在foreach循环中迭代Dictionary键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是..如果特定键与我的字符串匹配,那么我想显示字典值..

what i want to do is .. if perticular key matches with my string then i want to display that dictionaries value ..

推荐答案

你不需要循环通过字典。

您可以检查字典键是否包含该键值,

如果确实如此,则直接访问它。



例如

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");
}


不需要foreach循环这样做

no need for foreach loop do it like this
 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


Zafar几乎是。这样更好:

Zafar is almost right. This is better:
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


这篇关于如何在foreach循环中迭代Dictionary键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆