Serge Harrison Serge Harrison - 4 months ago 54
C# Question

c# dictionary select value from key

I've been searching through here and I realize that similar questions have been asked before, and I've gone over several, but what seems to be correct doesn't seem to be working for.

I have the following method which pulls a set of key value pairs in a DataSet gathered from a SQL query.

public static Dictionary<string, string> LoadConfiguration()
DataSet sqlResults = data.GetSettings();

Dictionary<string, string> dict =
new Dictionary<String, String>();

foreach (DataRow dr in sqlResults.Tables[0].Rows)
dr.Field<string>("key"), dr.Field<string>("value")

return dict;

It's as simple as it gets as far as I can see, but I've never actually worked with a dictionary before as I'm relatively new to any kind of real programming.

I know that my Dictionary has the expected data, because if I iterate through it with a foreach, it gives me the expected results

foreach (KeyValuePair<string, string> i in MyStuff.Configuration.LoadConfiguration())
Console.WriteLine("Key = " + i.Key + " Value = " + i.Value);

which gives me the following which is all I've implemented so far

Key = EnableLdap Value = false
Key = LdapPath Value = LDAP://DC=some,DC=domain,DC=com
Key = SessionTimeout Value = 60

But I only want to select a specific value from a key named EnableLdap for example

My understanding is that both the following methods would be correct. But when I try this way, I get a KeyNotFoundException

Dictionary<string,string> dict = MyStuff.Configuration.LoadConfiguration();

If I try this I get a [InvalidOperationException: Sequence contains no matching element]

Dictionary<string,string> dict = MyStuff.Configuration.LoadConfiguration();
Console.WriteLine(dict.Single(s => s.Key == "EnableLdap").Value);

And if I try this I just get nothing

string value = "";

if (dict.TryGetValue("EnableLdap", out value))
dict["EnableLdap"] = value;


I'm pretty certain I'm missing something simple here and the answer will result in a facepalm


It is one of these 2 issues.

  1. The key does not exist in the dictionary, this could be due to a spelling mistake or even a leading/trailing space or something of that nature.
  2. The key exists but is cased differently than you think it is.

For option 2 you can ensure that casing is not an issue by providing a StringComparer to the dictionary as an argument in the constructor.

Dictionary<string, string> dict = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);

The above code snippet will ensure that the dictionary creates the hash for each key based on the ordinal case insensitive representation of the string key. This will allow for the following example to pass:

dict["enableldap"] = "true";

See StringComparer for more options.