按键获取字典值

Mat*_*Zoc 153 c# dictionary key

如何通过键功能获取字典值

我的功能代码是这个(和我尝试但不起作用的命令):

static void XML_Array(Dictionary<string, string> Data_Array)
{
    String xmlfile = Data_Array.TryGetValue("XML_File", out value);
}
Run Code Online (Sandbox Code Playgroud)

我的按钮代码就是这个

private void button2_Click(object sender, EventArgs e)
{
    Dictionary<string, string> Data_Array = new Dictionary<string, string>();
    Data_Array.Add("XML_File", "Settings.xml");

    XML_Array(Data_Array);
}
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:
XML_Array函数上是
字符串xmlfile = Settings.xml

Blo*_*ard 207

这很简单:

String xmlfile = Data_Array["XML_File"];
Run Code Online (Sandbox Code Playgroud)

请注意,如果字典没有等于的键"XML_File",则该代码将引发异常.如果您想先检查,可以像这样使用TryGetValue:

string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
   // the key isn't in the dictionary.
   return; // or whatever you want to do
}
// xmlfile is now equal to the value
Run Code Online (Sandbox Code Playgroud)


Fre*_*kyB 61

为什么不在字典上使用键名,C#有这个:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 dict.Add("UserID", "test");
 string userIDFromDictionaryByKey = dict["UserID"];
Run Code Online (Sandbox Code Playgroud)

如果你看一下提示建议:

在此输入图像描述

  • 如果密钥不存在,它将引发异常。这就是为什么其他人的答案建议您使用TryGetValue的原因。 (3认同)

das*_*ght 26

那不是怎么回事TryGetValue.它返回truefalse基于是否找到密钥,并在密钥存在时将其out参数设置为相应的值.

如果你想检查密钥是否存在,并在缺少密钥时做一些事情,你需要这样的东西:

bool hasValue = Data_Array.TryGetValue("XML_File", out value);
if (hasValue) {
    xmlfile = value;
} else {
    // do something when the value is not there
}
Run Code Online (Sandbox Code Playgroud)


小智 16

Dictionary<String,String> d = new Dictionary<String,String>();
        d.Add("1","Mahadev");
        d.Add("2","Mahesh");
        Console.WriteLine(d["1"]);// it will print Value of key '1'
Run Code Online (Sandbox Code Playgroud)


aqw*_*ert 6

static void XML_Array(Dictionary<string, string> Data_Array)
{
    String value;
    if(Data_Array.TryGetValue("XML_File", out value))
    {
     ... Do something here with value ...
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

static String findFirstKeyByValue(Dictionary<string, string> Data_Array, String value)
{
    if (Data_Array.ContainsValue(value))
    {
        foreach (String key in Data_Array.Keys)
        {
            if (Data_Array[key].Equals(value))
                return key;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)