This is a portion of a console app I was using to investigate the Dictionary class and its methods. I was running into issues with Keys not being found within a dictionary that was being auto-generated from incoming web service data, data which I of course had no control over. There were several clients hitting the service which were not using the outlined parameter names with the correct casing. The Dictionary class in .Net uses hashing algorithms to create unique Keys from the key that is entered when the Key/Value pair is added. Because of this hashing the same string with different casing will generate a different unique key. In order to overcome this I found all you have to do is pass in StringComparer.CurrentCultureIgnoreCase in the constructor of the Dictionary at initialization and from that point on it no longer cares about the casing.
try
{
Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
dictionary.Add("KeyOne", "Value");
dictionary.Add("keyone", "Value");
foreach (KeyValuePair<string, string> valuePair in dictionary)
{
Console.WriteLine(
string.Format("Key: {0}, Value: {1}",
valuePair.Key,
valuePair.Value));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
Published by