C# Dictionary<K,V> not using custom comparer

Ethan Strauss 21 Reputation points
2020-12-31T22:07:53.697+00:00

I have a Dictionary<string, Name> (Name is an Excel Named Range, but I don't think that matters.) which I have defined a Customer IEqualityComparer. The dictionary appears not to be using this comparer. Any ideas why?

Here is the dictionary instantiation:
  MarkerComparisonNamedRangesByMaker = new Dictionary<string, Name>(new Promega.ResearchAndDevelopment.Utilities.PermissiveStringEqualityComparer());


Here is some code I wrote to test what was going on:
           List<string> exploration = new List<string>();
                exploration.Add($"Dictionary Comparer: {detailWriter.MarkerComparisonNamedRangesByMaker.Comparer}");
                exploration.Add($"Marker name: {result.Marker.Name}");
                //If the dictionary was using the comparer this should be true
                exploration.Add($"Dictionary contains key?: { detailWriter.MarkerComparisonNamedRangesByMaker.ContainsKey(result.Marker.Name)}");
                //And should absolutely be the same as this
                exploration.Add($"Name is in Dictionary with comparer?: { detailWriter.MarkerComparisonNamedRangesByMaker.Any(i => detailWriter.MarkerComparisonNamedRangesByMaker.Comparer.Equals(i.Key, result.Marker.Name))}");
                try
                {
                    exploration.Add($"Can get from dictionary?: { detailWriter.MarkerComparisonNamedRangesByMaker[result.Marker.Name].Name}");
                }
                catch
                {
                    exploration.Add($"Can get from dictionary?: Nope!");
                }
                string whatDidWeFind = string.Join("\r\n", exploration);

And here is the output from the exploration.
Dictionary Comparer: Promega.ResearchAndDevelopment.Utilities.PermissiveStringEqualityComparer
Marker name: Mono-27
Dictionary contains key?: False
Name is in Dictionary with comparer?: True
Can get from dictionary?: Nope!

I think this clearly demonstrates that it is not using the comparer. Why?

Thanks!
Ethan

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,007 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ethan Strauss 21 Reputation points
    2021-01-03T22:50:05.7+00:00

    Thanks you! I never thought about GetHash. The equality methods use case insensitive comparisons, but the has code didn't. I have now fixed it.
    Ethan

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.