Overriding Equals method for fast search

Override Equals method for fast search on List

We use IList very often to hold collections of items in .net. IList is a generic list that holds items of Type T.

IList Contains method can be used to determine if object obj of Type T is available on the list or not. By default it matches all the Fields of the object.

If you matching Criteria is only one field for eg: Id of the User object, you can override the Equals method of User class so that when matching two instances of User class only userid is checked.

Here is the C# code

public class User : INotifyPropertyChanged {

       private string name;       

       public Guid UserId { get; private set; }

        public virtual string Name

        {

            get

            {

                return name;

            }

            set

            {

                name = value;

                FirePropertyChangedEvent("Name");

            }

 public virtual event PropertyChangedEventHandler PropertyChanged;

        private void FirePropertyChangedEvent(string propertName) {

            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertName));

        }

        public override bool Equals(object obj) {

            if (this == obj) return true;

            var other = obj as User;

            if (other == null) return false;

            return UserId.Equals(other.UserId);

        }

    }

Calls on IList Contains method increases performance if you only check only one field (Most times only checking unique field like id makes sense rather than checking all the available fields of the object (which is default behaviour))

, , ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Share to Facebook Share to Twitter Stumble It Share on Tumblr Digg More...