如何通过函数上的键获取字典值?

我的函数代码(和我尝试的命令不工作):

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

我的按钮代码:

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

我想对XML_Array函数的变量是:

string xmlfile = "Settings.xml":

当前回答

我使用类似于dasblinkenlight的方法在函数中从包含加载到Dictionary中的JSON数组的Cookie返回一个键值,如下所示:

    /// <summary>
    /// Gets a single key Value from a Json filled cookie with 'cookiename','key' 
    /// </summary>
    public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
    {
        //CALL COOKIE VALUES INTO DICTIONARY
        Dictionary<string, string> dictCookie =
        JsonConvert.DeserializeObject<Dictionary<string, string>>
         (MyCookinator.Get(_CookieName));

        string value;
        if (dictCookie.TryGetValue( _key, out value))
        {
            return value;
        }
        else
        {
            return "0";
        }

    }

其中“MyCookinator.Get()”是另一个简单的Cookie函数,获取http Cookie的整体值。

其他回答

Dictionary<int,string> dict = new Dictionary<int,string>{
  {1,"item1"},
  {2,"item2"},
  {3,"item3"},
}

int key = 2 // for example
string result = dict.ContainsKey(key) ? dict[key] : null;
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;
}
if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];
static void XML_Array(Dictionary<string, string> Data_Array)
{
    String value;
    if(Data_Array.TryGetValue("XML_File", out value))
    {
        // ... Do something here with value ...
    }
}

我使用类似于dasblinkenlight的方法在函数中从包含加载到Dictionary中的JSON数组的Cookie返回一个键值,如下所示:

    /// <summary>
    /// Gets a single key Value from a Json filled cookie with 'cookiename','key' 
    /// </summary>
    public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
    {
        //CALL COOKIE VALUES INTO DICTIONARY
        Dictionary<string, string> dictCookie =
        JsonConvert.DeserializeObject<Dictionary<string, string>>
         (MyCookinator.Get(_CookieName));

        string value;
        if (dictCookie.TryGetValue( _key, out value))
        {
            return value;
        }
        else
        {
            return "0";
        }

    }

其中“MyCookinator.Get()”是另一个简单的Cookie函数,获取http Cookie的整体值。