Why does String.IndexOf(String, StringComparison)
require a StringComparison
and not allow for the more general StringComparer
, or even just IComparer<T>
or IEqualityComparer<T>
?
I made a custom StringComparer
to use with several dictionaries, and I want to use it in other parts of my project but I can't find a good way to do that without making lots of extensions methods, if those would even work.
This is the comparer I made. It was based roughly on this recommendation: Implementing custom IComparer with string
Also note that ModifyString is a WIP. I expect to add more things there, based on the input that I'm comparing against. I also know that it's expensive, but I'm just looking for a solution ATM, not performance.
public class CustomComparer : StringComparer
{
public override int Compare(string x, string y)
{
return StringComparer.Ordinal.Compare(ModifyString(x), ModifyString(y));
}
public override bool Equals(string x, string y)
{
if (ModifyString(x).Equals(ModifyString(y)))
return true;
else
return false;
}
public override int GetHashCode(string obj)
{
if (obj == null)
return 0;
else
return ModifyString(obj).GetHashCode();
}
private string ModifyString(string s)
{
//I know this code is expensive/naaive, your suggestions are welcome.
s = s.ToLowerInvariant();
s = s.Trim();
s = Regex.Replace(s, @"\s+", " ");//replaces all whitespace characters with a single space.
return s;
}
}