[c#] get dictionary value by key

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

This question is related to c# dictionary key

The answer is


That is not how the TryGetValue works. It returns true or false based on whether the key is found or not, and sets its out parameter to the corresponding value if the key is there.

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
}

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


static void XML_Array(Dictionary<string, string> Data_Array)
{
    String value;
    if(Data_Array.TryGetValue("XML_File", out value))
    {
     ... Do something here with 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);
            }
          static void XML_Array(Dictionary<string, string> Data_Array)
            {
                String xmlfile = Data_Array["XML_File"];
            }

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:

    /// <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.


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'

Here is an 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();
    }
...

This solution works with SortedDictionary also.


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"];

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?