I'm trying to implement an IEqualityComparer<string>
which basically compares two strings in a way that,(let's assume we have two strings x
and y
) if x
starts with y
or y
starts with x
they should be treated as equal.
public bool Equals(string x, string y)
{
return x.StartsWith(y) || y.StartsWith(x);
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
Ofcourse implementing the Equals
method is pretty easy.But the GetHashCode
is not, I couldn't think any way to implement it correctly.I have written a test program like this:
string[] values = {"hell", "hello", "foo", "fooooo"};
var result = values.Distinct(new StringComparer());
foreach(var x in result)
Console.WriteLine(x);
And I get the wrong result because of GetHashCode
:
hell
hello
foo
fooooo
Obviously I can force calling Equals
method by returning same value from the GetHashCode
for all values but I wanna know if there is another way to implement it because the performance is critical. Is there a way to implement GetHashCode
method correctly for my situation ?
Note: I know it is vague but I couldn't find a better title, if you have a better idea you are free to edit.
Edit: I'm going to use this logic with web urls. In my situation first 20 characters are equal. For example:
http://www.foo.com/bar?id=3
http://www.foo.com/bar?id=3&fooId=23