Dictionary<K,V> and Case Insensitive key compare?

  • Thread starter William Stacey [MVP]
  • Start date
W

William Stacey [MVP]

Trying to figure out Dictionary<> and using CaseInsensitive Comparer<> like
I did with normal Hashtable. The Hashtable can take a case insenstive
Comparer and a Case insensitive HashCode provider. It seems the HashCode
provider is lost or not needed in the Generic Dictionary anymore so
wondering if this is how you do the same:

Dictionary<string, Node> nodes = new Dictionary<string, Node>( new
StringCompInsensitive() );
....

public class StringCompInsensitive : IComparer<string>
{
public StringCompInsensitive()
{
}

public int Compare(string x, string y)
{
return String.Compare(x, y, true);
}

public bool Equals(string x, string y)
{
return String.Compare(x, y, true) == 0;
}

public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}

1) Is this insensitive comparer the best way to implement it? I was
wondering if Equals could be optimized for ref equality or something.

2) Does the Dictionary call Equals first on string and if not equal call
Compare? How does that work or GetHashCode fit in.

3) Do I also need a CaseInsensitive Hash Code provider in GetHashCode or
should this work ok? Need some clarity here.

TIA!

Note: Also posted this at microsoft.private.whidbey.generics, but after the
fact figured I would get more joy here.
 
K

Kevin Yu [MSFT]

Hi William,

This probably is not documented well enough but what you should be using is
System.StringComparer. It has static properties on it to get
InvariantCulture, InvariantCultureIgnoreCase, CurrentCulture,
CurrentCultureIgnoreCase, Ordinal, and OrdinalIgnoreCase comparers that
implement IComparer<string>.

1) You should just use the built in StringComparer. Like in
Dictionary<string, Node> nodes = new Dictionary<string, Node>(
StringComparer.OnvariantCultureIgnoreCase);

2) Dictionary only uses Equals and GetHashCode. It never calls Compare. The
hash is used to find the hashtable bucket.

3) You don't have to have it.

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top