简体   繁体   English

使用IEqualityComparer <T> 确定唯一性

[英]Using IEqualityComparer<T> to determine uniqueness

I am using a HashSet. 我正在使用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! 谢谢您的帮助!

I believe the problem is that in your Add() code, you first remove the existing item, then add the new (duplicated) one. 我相信问题在于,在您的Add()代码中,您首先要删除现有项目,然后添加新的(重复的)项目。 This will always be successful since there aren't any duplicates which is why it returns true . 这将始终是成功的,因为没有重复项,因此它返回true Remove the Remove() call and it will fix itself. 删除Remove()调用,它将自行修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM