Home C# Overriding Equals method for fast search

Tips and tricks

Site statistics

Members : 19
Content : 104
Content View Hits : 18543

Who's Online

We have 12 guests online
Overriding Equals method for fast search PDF Print E-mail
User Rating: / 0
PoorBest 
Articles - C#
Written by Dot4Pro   
Wednesday, 25 November 2009 17:24

 Override Equals method for fast search on List

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

IList<T> 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))  

 

 

Add comment


Security code
Refresh

feed-image Feed Entries