get dictionary value by key

Matei Zoc picture Matei Zoc · Aug 29, 2012 · Viewed 618.6k times · Source

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

Answer

Blorgbeard is out picture Blorgbeard is out · Aug 29, 2012

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