get dictionary value by key

2019-01-13 23:40发布

How can I get the dictionary value by key on function

my function code is this ( and the command what I try but didn't work ):

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

my button code is this

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

I want something like this:
on XML_Array function to be
string xmlfile = Settings.xml

10条回答
一夜七次
2楼-- · 2019-01-14 00:02

Why not just use key name on dictionary, C# has this:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 dict.Add("UserID", "test");
 string userIDFromDictionaryByKey = dict["UserID"];

If you look at the tip suggestion:

enter image description here

查看更多
戒情不戒烟
3楼-- · 2019-01-14 00:03
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;
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-14 00:07
if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];
查看更多
姐就是有狂的资本
5楼-- · 2019-01-14 00:08
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'
查看更多
地球回转人心会变
6楼-- · 2019-01-14 00:13

Here is example which I use in my source code. I am getting key and value from Dictionary from element 0 to number of elements in my Dictionary. Then I fill my string[] array which I send as a parameter after in my function which accept only params string[]

    Dictionary<string, decimal> listKomPop = addElements();
    int xpopCount = listKomPop.Count;
    if (xpopCount > 0)
    {
        string[] xpostoci = new string[xpopCount];
        for (int i = 0; i < xpopCount; i++)
        {
            /* here you have key and value element */
            string key = listKomPop.Keys.ElementAt(i);
            decimal value = listKomPop[key];

            xpostoci[i] = value.ToString();
        }
    ...

Hope this will help you and the others. This solution works with SortedDictionary also.

Kind regards,

Ozren Sirola

查看更多
\"骚年 ilove
7楼-- · 2019-01-14 00:14
static void XML_Array(Dictionary<string, string> Data_Array)
{
    String value;
    if(Data_Array.TryGetValue("XML_File", out value))
    {
     ... Do something here with value ...
    }
}
查看更多
登录 后发表回答