326

How can I get the dictionary value by a key on a function?

My function code (and the command I try doesn't work):

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

My button code:

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 on the XML_Array function the variable to be:

string xmlfile = "Settings.xml":
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matei Zoc
  • 3,739
  • 3
  • 16
  • 18

12 Answers12

437

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
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
147

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FrenkyB
  • 6,625
  • 14
  • 67
  • 114
  • 10
    It throws an exception if the key does not exist. That is why other people's answers suggest that you should use TryGetValue. – Ladislav Ondris Jul 31 '18 at 10:38
  • 1
    I don't think this is the reason that others are suggesting TryGetValue. My solution is simplification, which I was not aware of. When I've found it out, I've pasted it here. And it seems that a lot of others didn't know about that also. Otherwise, they could also paste this answer and add that throws exception if key doesn't exist. Anyway, thanks for warning. – FrenkyB Aug 02 '18 at 10:31
  • 1
    For some reason I always forget this with Dictionaries... Like it doesn't seem like it should be this straightforward. – Ortund Jan 16 '21 at 12:46
  • Still a good solution when you know that values will always exiist. If not, it would still recommend the answers that suggest using TryGetValue(). – Koenman Mar 17 '21 at 12:27
  • If your code is throwing an exception because the key does not exist - where you are trying to "get the value from a dictionary by key", there is possibly an underlying issue with your code. Your key range should be limited to keys that exist in the dictionary. – IamSierraCharlie Dec 19 '22 at 04:17
39

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
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
32
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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahadev Mane
  • 810
  • 8
  • 11
  • An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/46582244/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Nov 08 '21 at 04:16
12
static void XML_Array(Dictionary<string, string> Data_Array)
{
    String value;
    if(Data_Array.TryGetValue("XML_File", out value))
    {
        // ... Do something here with value ...
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aqwert
  • 10,559
  • 2
  • 41
  • 61
6
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;
}
Jacek Lisiński
  • 123
  • 1
  • 6
  • How does that answer the question? *"How can I get the dictionary value by a key"* An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/21003143/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Nov 08 '21 at 04:09
  • Is this the answer to [a different question](https://stackoverflow.com/questions/2444033/get-dictionary-key-by-value)? – Peter Mortensen Nov 08 '21 at 04:10
3
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"];
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
  • An explanation would be in order. E.g., what is the idea/gist? What was changed? What was the fix? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/21310319/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Nov 08 '21 at 04:12
3

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Shixx
  • 49
  • 7
3
Dictionary<int,string> dict = new Dictionary<int,string>{
  {1,"item1"},
  {2,"item2"},
  {3,"item3"},
}

int key = 2 // for example
string result = dict.ContainsKey(key) ? dict[key] : null;
Andy Chang
  • 49
  • 4
  • 2
    This would search for the key twice in the dictionary. Why not use the out parameter of TryGetValue instead of searching a second time? Even with your code: Why even use TryGetValue instead of ContainsKey if you want to go that route? – BDL Apr 22 '21 at 08:20
2

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.

Martin Sansone - MiOEE
  • 4,281
  • 1
  • 29
  • 31
0

(I posted this on another question and I don't know how to link to that so here it is) A Dictionary<K,V> extension that works. I have been using it for a long time::

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

And use 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}");
}
Gogu CelMare
  • 699
  • 6
  • 15
-2
if (Data_Array["XML_File"] != "") String xmlfile = Data_Array["XML_File"];
  • You have got some [explaining](https://stackoverflow.com/posts/54096267/edit) to do. (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Nov 08 '21 at 04:33