Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the field of an object as a generic Dictionary key

People also ask

Can I use object as dictionary key?

Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions. However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once.

Can we use object as key in dictionary c#?

The keys in a dictionary can be a reference type, i.e., objects. When an object is used as the key, the virtual methods "GetHashCode()" & "Equals()" can change how the dictionary search for the entries depending on if they are overridden, and how they are overridden.

Is generic a dictionary?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

Can a dictionary key be an array?

A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.


By default, the two important methods are GetHashCode() and Equals(). It is important that if two things are equal (Equals() returns true), that they have the same hash-code. For example, you might "return FooID;" as the GetHashCode() if you want that as the match. You can also implement IEquatable<Foo>, but that is optional:

class Foo : IEquatable<Foo> {
    public string Name { get; set;}
    public int FooID {get; set;}

    public override int GetHashCode() {
        return FooID;
    }
    public override bool Equals(object obj) {
        return Equals(obj as Foo);
    }
    public bool Equals(Foo obj) {
        return obj != null && obj.FooID == this.FooID;
    }
}

Finally, another alternative is to provide an IEqualityComparer<T> to do the same.


As you want the FooID to be the identifier for the group, you should use that as key in the dictionary instead of the Foo object:

Dictionary<int, List<Stuff>>

If you would use the Foo object as key, you would just implement the GetHashCode and Equals method to only consider the FooID property. The Name property would just be dead weight as far as the Dictionary was concerned, so you would just use Foo as a wrapper for an int.

Therefore it's better to use the FooID value directly, and then you don't have to implement anything as the Dictionary already supports using an int as a key.

Edit:
If you want to use the Foo class as key anyway, the IEqualityComparer<Foo> is easy to implement:

public class FooEqualityComparer : IEqualityComparer<Foo> {
   public int GetHashCode(Foo foo) { return foo.FooID.GetHashCode(); }
   public bool Equals(Foo foo1, Foo foo2) { return foo1.FooID == foo2.FooID; }
}

Usage:

Dictionary<Foo, List<Stuff>> dict = new Dictionary<Foo, List<Stuff>>(new FooEqualityComparer());

For Foo you will need to override object.GetHashCode() and object.Equals()

The dictionary will call GetHashCode() to calculate a hash bucket for each value and Equals to compare whether two Foo's are identical.

Make sure to calculate good hash codes (avoid many equal Foo objects having the same hashcode), but make sure two equals Foos have the same hash code. You might want to start with the Equals-Method and then (in GetHashCode()) xor the hash code of every member you compare in Equals.

public class Foo { 
     public string A;
     public string B;

     override bool Equals(object other) {
          var otherFoo = other as Foo;
          if (otherFoo == null)
             return false;
          return A==otherFoo.A && B ==otherFoo.B;
     }

     override int GetHashCode() {
          return 17 * A.GetHashCode() + B.GetHashCode();
     }
}

What about Hashtable class!

Hashtable oMyDic = new Hashtable();
Object oAnyKeyObject = null;
Object oAnyValueObject = null;
oMyDic.Add(oAnyKeyObject, oAnyValueObject);
foreach (DictionaryEntry de in oMyDic)
{
   // Do your job
}

In above way, you can use any object (your class object) as a generic Dictionary key :)