Hassan Ahmadi
Hassan Ahmadi

Reputation: 706

What is the most optimized way to implement an ignore case dictionary in c#

Imagine we have a custom dictionary class which is derived from Dictionary<string, object>. Dictionary is case-insensitive about keys and elements arrange is not important. So what is the most optimized way to compare two instance of this class, or in another word what is the best override of Equals method in this class.

I tried to use these two ways to implement this class. But i'm not sure which way is better than the other. Please help me to choose the best way or correct me if i made any mistake.

First implementation:

public class CustomeDictionary : Dictionary<string, object>
{
    public CustomeDictionary() :
     base(StringComparer.InvariantCultureIgnoreCase)
    {
    }

    public CustomeDictionary(CustomeDictionary CustomeDictionary) :
     base(CustomeDictionary, StringComparer.InvariantCultureIgnoreCase)
    {
    }

    public bool Equals(CustomeDictionary other)
    {
        if (other is null)
            return false;

        if (Count != other.Count)
            return false;

        foreach (var (key, value) in this)
            if (!other.ContainsKey(key) || !value.Equals(other[key]))
                return false;

        return true;
    }

    public override bool Equals(object? obj)
    {
        return Equals(obj as CustomeDictionary);
    }

    public override int GetHashCode()
    {
        return this.Sum(i => (i.Key.ToLower(), i.Value).GetHashCode());
    }
}

The second way was to use another class which is an implementation of IEqualityComparer<KeyValuePair<string, object>> which can help to use some efficient Linq methods like Except to override the Equals and overload ==.

The EqualityComparer CustomClass

public class CustomKeyValuePair : IEqualityComparer<KeyValuePair<string, object>>
{
    public bool Equals(KeyValuePair<string, object> x, KeyValuePair<string, object> y)
        => GetHashCode(x) == GetHashCode(y);


    public int GetHashCode(KeyValuePair<string, object> obj)
    {
        var (key, value) = obj;
        return (key.ToLower(), value).GetHashCode();
    }
}

and I have used it like below in Equals:

   public bool Equals(CustomHashTable other)
   {
      return this.Except(other, new CustomKeyValuePair()).Any();
   }

Please help me to improve and refactor the code.

Upvotes: 1

Views: 109

Answers (0)

Related Questions