您可以创建一个忽略变音符号的自定义比较器:
class IgnoreUmlautComparer : IEqualityComparer<string>
{
Dictionary<char, char> umlautReplacer = new Dictionary<char, char>()
{
{'ä','a'}, {'Ä','A'},
{'ö','o'}, {'Ö','O'},
{'ü','u'}, {'Ü','U'},
};
Dictionary<string, string> pseudoUmlautReplacer = new Dictionary<string, string>()
{
{"ae","a"}, {"Ae","A"},
{"oe","o"}, {"Oe","O"},
{"ue","u"}, {"Ue","U"},
};
private IEnumerable<char> ignoreUmlaut(string s)
{
char value;
string replaced = new string(s.Select(c => umlautReplacer.TryGetValue(c, out value) ? value : c).ToArray());
foreach (var kv in pseudoUmlautReplacer)
replaced = replaced.Replace(kv.Key, kv.Value);
return replaced;
}
public bool Equals(string x, string y)
{
var xChars = ignoreUmlaut(x);
var yChars = ignoreUmlaut(y);
return xChars.SequenceEqual(yChars);
}
public int GetHashCode(string obj)
{
return ignoreUmlaut(obj).GetHashCode();
}
}
现在您可以将此比较器与以下Enumerable
方法一起使用Distinct
:
string[] allStrings = new[]{"voest","vost","vöst"};
bool allEqual = allStrings.Distinct(new IgnoreUmlautComparer()).Count() == 1;
// --> true