开发者

Dictonary.ContainsKey Comparison

I am trying to do something along the lines of the following:

class Test
{
     public string Name { get; set;}
     public string Location { get; set;}
     public Test(string name, string location)
     {
 开发者_开发知识库        Name = name;
         Location = location;
     }
}

Now, in a method in another class, I am trying to add these Test classes into a Dictionary with a KeyValuePair of

Dictionary<Test,int> resources = new Dictionary<Test,int>();
resources.Add(new Test("First Resource", "Home"), 1);

Now, what I am trying to do, and need to be able to do is:

bool contains = resources.ContainsKey(new Test("First Resource", "Home"));
resources[new Test("First Resource", "Home")] = 2;

As of now, this returns false. How can I get this to return true?

I have tried overriding the Equals function of my Test class and even implementing IComparible and doing custom comparisons.


You need to override GetHashCode in your Test class, add the following to your class:

public override int GetHashCode()
{
    return (Name+Location).GetHashCode();
}

This will ensure that any two Test instances have the same hash only if the concatenation of Name and Location are the same. You could use other strategies for this, however, this is the simplest form.


You need to implement GetHashCode and Equals in the key class or provide an IEqualityComparer<Test> implementation in the constructor of the dictionary.

In the case of the comparer, you would define proper GetHashCode and Equals methods inside the comparer for Test, with the benefit that these implementations are not universal for all Test objects, but can be used at will when necessary (such as for use in dictionaries, hashsets, various Linq queries, etc.) By decoupling the equality and hashcode functions from the class, you are then free to use different implementations of the comparer as the need arises.

(For a good set of guidelines on GetHashCode, please visit this blog.)


Dictionary uses GetHashCode of the key to determine in which data bucket to store an object, and then Equals to make sure that the objects are actually equal. In other words, for this to work, you will need to implement GetHashCode() and Equals for your type.

It is considered good practice to make objects used for keys in a dictionary immutable. If the object changes, its hashcode changes, and you might not be able to find it in the dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜