Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dictionary value by key

Tags:

c#

dictionary

key

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:

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

Just use the key name on the 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


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
}

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'

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

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

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.