Anand Anand - 16 days ago 5
C# Question

KeyValueComparer based on key

I have 2 key value comparers - in both I am using key to compare, which is string.
Can I use generic for the value - so instead of have 2 classes I can have only 1?

So instead of the classes below I wish I could have only 1 class

class KvpComparer : IEqualityComparer < KeyValuePair < string, T>>
{
...
}

class KvpComparer : IEqualityComparer<KeyValuePair<string, Tuple<string, string>>>
{
public bool Equals(KeyValuePair<string, Tuple<string, string>> x, KeyValuePair<string, Tuple<string, string>> y)
{
return x.Key.Equals(y.Key);
}

public int GetHashCode(KeyValuePair<string, Tuple<string, string>> obj)
{
return obj.Key.GetHashCode();
}
}

class KvpComparer2 : IEqualityComparer<KeyValuePair<string, string>>
{
public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
{
return x.Key.Equals(y.Key);
}

public int GetHashCode(KeyValuePair<string, string> obj)
{
return obj.Key.GetHashCode();
}
}

Answer

As the comparers differ only in the value type of the KeyValuePair, you could use a type parameter for the value type to generalize the two comparers into a single generic type as follows.

class KvpComparer<T> : IEqualityComparer<KeyValuePair<string,T>> where T : class
{
    public bool Equals(KeyValuePair<string,T> x, KeyValuePair<string,T> y)
    {
        return x.Key.Equals(y.Key);
    }

    public int GetHashCode(KeyValuePair<string, T> obj)
    {
        return obj.Key.GetHashCode();
    }
}
Comments