Bas Bas - 1 month ago 5
C# Question

C# checking if duplicate in dictionary

This isn't a duplicate, since I'm using objects as key

I'm trying to create a dictionary which checks if the object that's being inserted is a duplicate, and if it is, it'll increase it's value.
My dictionary looks like this:

Dictionary<Object, int> output = new Dictionary<Object, int>();


In this example, Object is the object I want to check if it's a duplicate. The integer stands for a 'weight' value, this is used further in my application.

How do I check if an object is a duplicate, and if it is how do I increase this integer?

Thanks in advance!

Answer

Here is efficient one. People often forget about TryGetValue.

Dictionary<Object, int> output = new Dictionary<Object, int>();
int count;
if(output.TryGetValue(keyObject, out count))
{
     output[keyObject] = count + 1;
}
else
{
     output.Add(keyObject, 1);
}

Object is reference type, so even if your objects have same values, they can reside at different positions in memory. For this to work with objects, you should override Equals and GetHashCode methods for your concrete class implementation. For example:

public class MyClass
{
    public int Value {get;set;}

    public override int GetHashCode() { return Value.GetHashCode(); }
    public override bool Equals(object other){return ((MyClass)other).Value.Equals(Value); }
}
Comments