Matthew Cox
Matthew Cox

Reputation: 13672

Using IEqualityComparer<T> to determine uniqueness

I am using a HashSet. I want to ensure that I don't have duplicate values. However, I am able to do so at the present moment.

[Serializable()]
public class SafetyObsDS
{
    public int Count
    {
        get { return set.Count; }
    }

    HashSet<CompResults> set;

    public SafetyObsDS()
    {
        set = new HashSet<CompResults>(new CompareToComparer());
    }

    public bool Add(CompResults cr)
    {
        set.Remove(cr);
        return set.Add(cr);
    }

    public bool Remove(CompResults cr)
    {
        return set.Remove(cr);
    }

    [Serializable()]
    private class CompareToComparer : IEqualityComparer<CompResults> 
    {
        public CompareToComparer() {}

        public bool Equals(CompResults cr1, CompResults cr2) 
        {
            return (cr1.CompareTo(cr2) == 0);
        }

        public int GetHashCode(CompResults cr)
        {
            return (cr.SectionID);
        }
    }
}

[Serializable()]
public class CompResults : IComparable
{
    public int SectionID { get; set; }

    public ComResults(int sectID)
    {
        SectionID = sectID;
    }

    public int CompareTo(object obj)
    {
        return SectionID - (obj as CompResults).SectionID;
    }

}

I left the constructors and additional unnecessary code such as other fields out When I perform the following operations, I receive undesired results:

Add(new CompResults(1));     Result: true
Add(new CompResults(1));     Result: true  <--- this is a dup and I don't want it to add
Remove(new CompResults(1));  Result: true

thanks for your help in advance!

Upvotes: 1

Views: 141

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134881

I believe the problem is that in your Add() code, you first remove the existing item, then add the new (duplicated) one. This will always be successful since there aren't any duplicates which is why it returns true. Remove the Remove() call and it will fix itself.

Upvotes: 3

Related Questions