简体   繁体   中英

Use “external” GetHashCode and Equals for Dictionary

I would like to use a class as key in a Dictionary which does not override Equals nor GetHashCode. It's a class from an external library which I don't want to modify.

So I am wondering if I can use custom "GetHashCode"/"Equals" implemantiotns just for one Dictionary? I was wondering if something like with C++ std::maps was possible

template < class Key,                      // map::key_type
           class T,                        // map::mapped_type
           class Compare = less<T>,        // map::key_compare
           class Alloc = allocator<T> >    // map::allocator_type
           > class map;

where Compare can be used to define custom comparison.

I don't want to derive from the class because the objects are created outside using the existing class.

I could create a class which contains the original class, but that changes the access to the Dictionary.

Thanks for your ideas!

Sure - you can implement IEqualityComparer<T> and pass that into the Dictionary<,> constructor . That's precisely the purpose of that constructor :)

For example:

public FooByNameEqualityComparer : IEqualityComparer<Foo>
{
    public int GetHashCode(Foo foo)
    {
        return foo.Name.GetHashCode();
    }

    public bool Equals(Foo x, Foo y)
    {
        return x.Name == y.Name;
    }
}

...

Dictionary<Foo, int> map = new Dictionary<Foo, int>(new FooByNameComparer());

You can pass a custom IEqualityComparer<TKey> to the constructor of the Dictionary<TKey,TValue> . The equality comparer must implement Equal and GetHashCode .

var dict = new Dictionary<MyKey,MyValue>(new MyKeyEqualityComparer());

You can use Dictionary Constructor (Int32, IEqualityComparer) ,

public Dictionary(
    int capacity,
    IEqualityComparer<TKey> comparer
)

where

comparer is:

implementation to use when comparing keys

In practise

  • you define a type that implements that interface
  • pass it to this ctor , so the method of that class are useed for equality identification of the keys of the dictionary.

Seems what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM