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

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

    You can use a custom Predicate for your class, such as:

    public class Account
    {
      public string name;
      public string password;
      public string newInfo;
    
      public class IndexOfName
      {
        private string _match = "";
    
        public IndexOfName()
        {
        }
    
        public Predicate Match(string match)
        {
          this._match = match;
          return IsMatch;
        }
    
        private bool IsMatch(Account matchTo)
        {
          if (matchTo == null)
          {
            return false;
          }
          return matchTo.Equals(this._match);
        }
      }
    }
    

    Then you can use it as follow:

    Account.IndexOf indexOf = new Account.IndexOf();
    int index;
    if ((index = AccountList.FindIndex(indexOf.Match("john"))) > 0)
    {
      // do something with John
    }
    if ((index = AccountList.FindIndex(indexOf.Match("jane"))) > 0)
    {
      // do something with Jane
    }
    

    You could even change the IndeOfName class to use a flag to switch between the type of info you are looking for. Ex: name or newInfo.

提交回复
热议问题