C# 通过键获取字典值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12169443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:19:39  来源:igfitidea点击:

get dictionary value by key

c#dictionarykey

提问by Matei Zoc

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_Arrayfunction to be
string xmlfile = Settings.xml

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

采纳答案by Blorgbeard is out

It's as simple as this:

就这么简单:

String xmlfile = Data_Array["XML_File"];

Note that if the dictionary doesn't have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:

请注意,如果字典没有等于 的键"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

回答by dasblinkenlight

That is not how the TryGetValueworks. It returns trueor falsebased on whether the key is found or not, and sets its outparameter to the corresponding value if the key is there.

这不是TryGetValue工作的方式。它根据是否找到键返回truefalse,如果键在,则将其out参数设置为相应的值。

If you want to check if the key is there or not and do something when it's missing, you need something like this:

如果您想检查密钥是否存在并在丢失时执行某些操作,您需要这样的东西:

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

回答by aqwert

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

回答by Jacek Lisiński

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

回答by Sumon Banerjee

          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);
            }
          static void XML_Array(Dictionary<string, string> Data_Array)
            {
                String xmlfile = Data_Array["XML_File"];
            }

回答by Martin Sansone - MiOEE

I use a similar method to dasblinkenlight's in a function to return a single key value from a Cookie containing a JSON array loaded into a Dictionary as follows:

我在函数中使用与 dasblinkenlight 类似的方法从包含加载到字典中的 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";
        }

    }

Where "MyCookinator.Get()" is another simple Cookie function getting an http cookie overall value.

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

回答by FrenkyB

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

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

 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

在此处输入图片说明

回答by Shixx

Here is example which I use in my source code. I am getting keyand valuefrom 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[]

这是我在源代码中使用的示例。我从字典中获取,从元素 0 到字典中的元素数。然后我填充我的 string[] 数组,我将它作为参数发送到我的函数中,它只接受 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.

希望这会帮助你和其他人。此解决方案也适用于 SortedDictionary。

Kind regards,

亲切的问候,

Ozren Sirola

奥兹伦·西罗拉

回答by Mahadev Mane

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'

回答by Abdalla Elmedani

if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];