如果是 string 类型的 key,可以使用 StringComparer.OrdinalIgnoreCase
var dict = new Dictionary<string, TrieNode>(StringComparer.OrdinalIgnoreCase);
但现在是 char 类型,需要的参数类型是 IEqualityComparer<char>
,请问如何实现?
目前实现的一个版本
public class CharComparer : IEqualityComparer<char>
{
public static CharComparer IgnoreCase { get; } = new CharComparer();
public bool Equals(char x, char y)
{
return char.IsLetter(x) && char.IsLetter(y) ?
char.ToLowerInvariant(x) == char.ToLowerInvariant(y)
: x.Equals(y);
}
public int GetHashCode([DisallowNull] char obj)
{
return char.IsLetter(obj) ?
char.ToLowerInvariant(obj).GetHashCode() :
obj.GetHashCode();
}
}
测试代码
[Fact]
public void CharComparer_test()
{
var dict = new Dictionary<char, TrieNode>(CharComparer.IgnoreCase);
dict.Add('a', new TrieNode('c'));
Assert.True(dict.ContainsKey('A'));
Assert.False(dict.ContainsKey('b'));
}
测试通过
Passed! - Failed: 0, Passed: 1