我需要从字符串中去除所有符号,以创建一个忽略标点符号的“IEqualityComparer”

Chr*_*isF 7 c# string iequalitycomparer

在我的应用程序的一部分中,我有一个选项可以显示当前艺术家不在音乐库中的专辑列表。为此,我调用音乐 API 来获取该艺术家的所有专辑列表,然后删除当前库中的专辑。

为了处理名称的不同大小写以及标题中丢失(或额外标点符号)的可能性,我写了一个IEqualityComparer.Except调用中使用:

var missingAlbums = allAbumns.Except(ownedAlbums, new NameComparer());
Run Code Online (Sandbox Code Playgroud)

这是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;
}
Run Code Online (Sandbox Code Playgroud)

这是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();
}
Run Code Online (Sandbox Code Playgroud)

当然,当字符串包含符号时​​会失败,因为我在获取哈希码之前没有删除它们,因此两个字符串(例如“Baa,baa,blacksheep”和“Baa baa Blacksheep”)仍然不相等,甚至转换为小写后。

我写了一个方法来去除符号,但这意味着我必须猜测这些符号实际上是什么。它适用于我迄今为止尝试过的情况,但我预计它最终会失败。我想要一种更可靠的删除符号的方法。

鉴于CompareOptions.IgnoreSymbols存在,是否有我可以调用的方法来从字符串中删除这些字符?或者失败了,一个将返回所有符号的方法?

我已经找到了IsPunctuation字符的方法,但我无法确定它认为是标点符号的内容是否与字符串比较选项认为是符号的内容相同。

Pet*_*iho 7

如果您打算使用CompareOptions枚举,我觉得您不妨将它与CompareInfo记录为专为以下目的设计的类一起使用:

定义与CompareInfo一起使用的字符串比较选项。

然后您可以使用GetHashCode(string, CompareOptions)该类中的Compare(string, string, CompareOptions)方法(如果您愿意,甚至可以使用该方法)。