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
C# Dictionary<K,V> not using custom comparer
Ethan Strauss
21
Reputation points
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
1 answer
Sort by: Most helpful
-
Ethan Strauss 21 Reputation points
2021-01-03T22:50:05.7+00:00