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

前端 未结 5 924
无人及你
无人及你 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:06

    Your object should implement the IEquatable interface and override the Equals method.

    public class Account : IEquatable
    {
        public string name;
        public string password;
        public string 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 String.Equals(this.newInfo, other.newInfo, 
                               StringComparison.OrdinalIgnoreCase);
        }
    }
    

提交回复
热议问题