How to use the IEqualityComparer

前端 未结 6 1903
一向
一向 2020-11-27 04:36

I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the fun

6条回答
  •  一个人的身影
    2020-11-27 04:59

    IEquatable can be a much easier way to do this with modern frameworks.

    You get a nice simple bool Equals(T other) function and there's no messing around with casting or creating a separate class.

    public class Person : IEquatable
    {
        public Person(string name, string hometown)
        {
            this.Name = name;
            this.Hometown = hometown;
        }
    
        public string Name { get; set; }
        public string Hometown { get; set; }
    
        // can't get much simpler than this!
        public bool Equals(Person other)
        {
            return this.Name == other.Name && this.Hometown == other.Hometown;
        }
    
        public override int GetHashCode()
        {
            return Name.GetHashCode();  // see other links for hashcode guidance 
        }
    }
    

    Note you DO have to implement GetHashCode if using this in a dictionary or with something like Distinct.

    PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.

    If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode defined (with override keyword).

提交回复
热议问题