在我的应用程序的一部分中,我有一个选项可以显示当前艺术家不在音乐库中的专辑列表。为此,我调用音乐 API 来获取该艺术家的所有专辑列表,然后删除当前库中的专辑。
为了应对名称的不同大小写以及标题中丢失(或额外标点符号)的可能性,我写了一个 IEqualityComparer
用于 .Except
称呼:
var missingAlbums = allAbumns.Except(ownedAlbums, new NameComparer());
这是Equals
方法:public bool Equals(string x, string y)
{
// Check whether the compared objects reference the same data.
if (ReferenceEquals(x, y)) return true;
// Check whether any of the compared objects is null.
if (x is null || y is null)
return false;
return string.Compare(x, y, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0;
}
这是GetHashCode
方法:public int GetHashCode(string obj)
{
// Check whether the object is null
if (obj is null) return 0;
// Make lower case. How do I strip symbols?
return obj.ToLower().GetHashCode();
}
当然,当字符串包含符号时,这会失败,因为我在获取哈希码之前没有删除它们,因此两个字符串(例如“Baa,baa,blacksheep”和“Baa baa Blacksheep”)仍然不相等,甚至转换为小写后。我写了一个方法来去除符号,但这意味着我必须猜测这些符号实际上是什么。它适用于我迄今为止尝试过的情况,但我希望它最终会失败。我想要一种更可靠的删除符号的方法。
鉴于
CompareOptions.IgnoreSymbols
存在,有没有我可以调用的方法可以从字符串中去除这些字符?或者失败了,一个将返回所有符号的方法?我找到了
IsPunctuation
字符的方法,但我无法确定它认为是标点符号的内容是否与字符串比较选项认为是符号的内容相同。
最佳答案
如果您打算使用 CompareOptions
枚举,我觉得你不妨将它与 CompareInfo
一起使用它被记录为专为以下目的设计的类:
Defines the string comparison options to use with CompareInfo.
然后你就可以使用
GetHashCode(string, CompareOptions)
来自该类的方法(如果您愿意,甚至可以使用 Compare(string, string, CompareOptions)
方法)。
关于c# - 我需要从字符串中去除所有符号以创建一个忽略标点符号的 `IEqualityComparer`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67994184/