C# KeyValuePair Tip: where are my keys again...

I had a small crazy issue today with a web app that I'm working on dealing with looking up keys and values in a C# KeyValuePair<string, Guid> generic object.

I was using it to look in a Dictionary<string, Guid> of users. Makes sense to populate dropdowns with on the server, and use as a callback in cache to not have to look at the database every page load right ?

For some reason it was not finding some Keys, or users in my case, and finding others. I narrowed it down to when you log in, what you type might not match the case that the system has for you.

And sure enough when I logged in with mcbeev it was not finding Mcbeev. That's pretty strange I thought, SQL isn't case sensitive. Ah but the default Dictionary<T, T> uses whatever the default comparison operator for string is.

I was using the following

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

And after switching to

Dictionary<string, Guid> dict = new Dictionary<string, Guid>(StringComparer.CurrentCultureIgnoreCase);

Viola! it worked. I had never bothered looking at the other constructors for Dictionary<T,T>. One of them allows you to pass whatever kind of comparer your heart desires.



Categories: Code

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments are closed

Blogroll

About Me

My name is Brian McKeiver and I'm a Software Developer and Partner at BizStream.

Audrey3.17.10 024Audrey3.17.10 023Audrey3.17.10 022Audrey3.17.10 021Audrey3.17.10 020Audrey3.17.10 019Audrey3.17.10 018Audrey3.17.10 017Audrey3.17.10 016Audrey3.17.10 015

Friend Tweets



View Mcbeev's profile on LinkedIn