使用IEqualityComparer <t>确定唯一性</t>

时间:2010-11-14 19:14:11

标签: c#

我正在使用HashSet。我想确保我没有重复的值。但是,我现在能够这样做。

[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;
    }

}

我离开了构造函数和其他不必要的代码,如其他字段 当我执行以下操作时,会收到不需要的结果:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

我认为问题在于,在Add()代码中,首先删除现有项目,然后添加新项目(重复项目)。这将始终是成功的,因为没有任何重复,这就是它返回true的原因。移除Remove()电话,它将自行修复。