Tuesday, December 10, 2013

remove an class object from a List in C# using IEqualityComparer

While removing simple datatypes(int, string, datetime etc) from List is quite simple it is not the case with Complex data types (some custom class) if it has to be removed from needs to be done using IEqualityComparer
 
I had this requirement where I needed to compare two set of Lists to identify which are the new sets of records to be created and which are the one already existing and therefore needs to be just updated.
 
A had a custom class called LookupNameValue which has certain name , value properties , now in order to compare two set of Lists in C# to find out I had to implement the IEqualityComparer for the LookupNameValue class
 
Sample code to implement IEqualityComparer : note that we have to implement method Equals and GetHashCode to use IEqualityComparer
public class ValueComparer : IEqualityComparer<LookupNameValue>
    {
 
        public bool Equals(LookupNameValue x,LookupNameValue y)
        {
            if (x.Value.Equals(y.Value))
                {
                    return true;
                }
                else
                {
                    return false;
                }
        }
        public int GetHashCode(LookupNameValue obj)
        {
            return obj.Name.GetHashCode();
        }
    }
 
Sample LookUpNameAndValue class
public class LookupNameValue : IComparable
    {
        private Guid _value;
        private string _name;
public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
 
        public Guid Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
            }
        }
}
 
Now once we have implemented the IEqualityComparer interface we need to use the same for filtering out the existing dataset.This is done by using Except method of the List
Sample Code to use the custom comparer
 
ValueComparer comparer = new ValueComparer();
IEnumerable<LookupNameValue> finalCreateTeamDataset = createTeamDatasetTemp.Except(updateDatasetToBeRemoved, comparer);
 
Where createTeamDatasetTemp and updateDatasetToBeRemoved are List of my generic class LookupNameValue
List<LookupNameValue> createTeamDatasetTemp = new List<LookupNameValue>();
List<LookupNameValue> updateDatasetToBeRemoved = new List<LookupNameValue>();
The filtered dataset could then be used as following
 
foreach (var data in finalCreateTeamDataset)
{
 //do ur job
}
 
Hope this is helpful to you all