How does List.IndexOf() perform comparisons on custom objects?

前端 未结 5 984
无人及你
无人及你 2021-01-18 00:45

I wrote a class of account objects and hold a static List of those account objects. My program loops through each account in the list, performing some

5条回答
  •  忘掉有多难
    2021-01-18 01:03

    One thing the accepted answer did not cover is you are supposed to override Equals(object) and GetHashCode() for IEquatable to work correctly. Here is the full implementation (based off of keyboardP's answer)

    public class Account : IEquatable
    {
        public string name;
        public string password;
        public string newInfo;
    
        private readonly StringComparer comparer = StringComparer.OrdinalIgnoreCase;
    
        public override bool Equals(object other)
        {
            //This casts the object to null if it is not a Account and calls the other Equals implementation.
            return this.Equals(other as Account);
        }
    
        public override int GetHashCode()
        {
            return comparer.GetHashCode(this.newInfo)
        }
    
        public bool Equals(Account other)
        {
           //Choose what you want to consider as "equal" between Account objects  
           //for example, assuming newInfo is what you want to consider a match
           //(regardless of case)
           if (other == null) 
                 return false;
    
           return comparer.Equals(this.newInfo, other.newInfo);
        }
    }
    

提交回复
热议问题