C#: Case Insensitive Generic Dictionary

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

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s