如何通过函数上的键获取字典值?
我的函数代码(和我尝试的命令不工作):
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":
(我在另一个问题上发布了这个,我不知道如何链接到它,所以在这里)
Dictionary<K,V>扩展。我已经用了很长时间了::
public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out
K key)
{
foreach (var entry in instance)
{
if (!entry.Value.Equals(value))
{
continue;
}
key = entry.Key;
return true;
}
key = default(K);
return false;
}
并使用as:
public static void Main()
{
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string value="two";
if (dict.TryGetKey(value, out var returnedKey))
Console.WriteLine($"Found Key {returnedKey}");
else
Console.WriteLine($"No key found for value {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的整体值。