Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 313
Kyle Uithoven Avatar asked Mar 24 '26 11:03

Kyle Uithoven


2 Answers

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.

like image 54
Candide Avatar answered Mar 26 '26 23:03

Candide


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.)

like image 38
Anthony Pegram Avatar answered Mar 26 '26 23:03

Anthony Pegram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!