覆盖类的Equals / GetHashCode以使用hashset Contains / ExceptWith / UnionWith

时间:2016-10-05 15:11:52

标签: c# linq

我目前有一个C#类,如下所示:

 namespace DBModel
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class ConnSrv
    {
        public int ID { get; set; }

        [Required]
        [StringLength(14)]
        public string Service { get; set; }

        [Required]
        [StringLength(14)]
        public string ConnectsToService { get; set; }

        public virtual Service Service1 { get; set; }

        public virtual Service Service2 { get; set; }
    }
}

在我的主程序中,我正在创建使用这些对象的哈希集。我遇到的问题是我希望能够在这些哈希集上使用Contains,Except,ExceptWith,UnionWith等运算符。

要使ConnSrv的对象被视为“相等”,Service和ConnectsToService值必须相等。因此,我意识到在某种程度上,我将不得不重写该类的Equals和GetHashCode运算符。我只是不确定如何这样做,无论是通过直接覆盖对象类,通过实现IEquatable或IEquatable,还是通过其他方法。下面是一些简单的例子,说明我希望最终结果一旦实现。如果我要离开场地,请告诉我。提前感谢您的时间。

        var testHS1 = new HashSet<ConnectingService>();

        testHS1.Add(test1);
        testHS1.Contains(test2); // Returns true

        var testHS2 = new HashSet<ConnectingService>();

        testHS2.Add(test1);
        testHS2.Add(test2);
        testHS2.Add(test3);

        testHS2.Except(testHS1); // Expect end result to only contain test3

3 个答案:

答案 0 :(得分:1)

以下是关于如何覆盖#include "stdafx.h" #include "stdio.h" void main() { int age[11]; float total = 0; int i = 1; float average; do { printf("# %d: ", i); scanf_s("%d", &age[i]); total = (total + age[i]); i = i + 1; } while (i <= 10); average = (total / 10); printf("Average = %.2f", average); }

guidelines
Equals

答案 1 :(得分:0)

  

我只是不知道该怎么做,无论是通过直接覆盖对象类,通过实现IEquatable或IEquatable,还是通过其他方法。

覆盖object.Equalsobject.GetHashCode就足够了。您也可以选择实现IEquatable,但对于参考类型,唯一的好处是分钟性能改进,因为您不必从{{1 }}。如果您实施object,则还必须覆盖IEquatableobject.Equals(object)

使用object.GetHashCode()时,更多重要的是遵循HashSet的规则,特别是两个“相等”对象具有相同的哈希码。

答案 2 :(得分:0)

谢谢Alex!这指向了正确的道路。我添加了以下代码,似乎是参加比赛。

    public override int GetHashCode()
    {
        return (Service.GetHashCode() * ConnectsToService.GetHashCode()).GetHashCode();
    }

    public bool Equals(ConnectingService c1)
    {
        return c1.Service == this.Service && c1.ConnectsToService == this.ConnectsToService;
    }
相关问题