Donate

How To Remove Duplicate Items In A List<T> Using IEqualityComparer<T>

Good evening.

Here's a simple demo on how to remove duplicate items in a List object using IEqualityComparer given that the generic list's type is complex. First we setup a simple model Employee class with Age, Name and Address properties.
class Employee
   {
      public int Age { get; set; }

      public string Name { get; set; }

      public string Address { get; set; }
   }
Next is to create a comparer class that implements IEqualityComparer interface.
class EmployeeComparer : IEqualityComparer<Employee>
   {
      public bool Equals(Employee emp1, Employee emp2)
      {
         if (Object.ReferenceEquals(emp1, emp2))
            return true;

         if (Object.ReferenceEquals(emp1, null) || Object.ReferenceEquals(emp2, null))
            return false;

         return (emp1.Age == emp2.Age) && (emp1.Name == emp2.Name) && (emp1.Address == emp2.Address);
      }

      public int GetHashCode(Employee obj)
      {
         return obj.Name.GetHashCode();
      }
   }
To make use of the IEqualityComparer class, add some records to the list object and remove the duplicate entries using LINQ Distinct method passing in an instance of the IEqualityComparer class.
class Program
   {
      static void Main(string[] args)
      {
         List<Employee> employees = new List<Employee>();

         employees.Add(new Employee()
         {
            Name = "James",
            Age = 25,
            Address = "PH"
         });


         employees.Add(new Employee()
         {
            Name = "Phil",
            Age = 30,
            Address = "UK"
         });

         employees.Add(new Employee()
         {
            Name = "James",
            Age = 25,
            Address = "PH"
         });

         employees.Add(new Employee()
         {
            Name = "Mike",
            Age = 18,
            Address = "US"
         });

         Console.WriteLine("Records before distinct operation");
         foreach (var item in employees)
         {
            Console.WriteLine(item.Name + " : " + item.Age + " : " + item.Address);
         }

         employees = employees.Distinct(new EmployeeComparer()).ToList();

         Console.WriteLine("\n\nRecords after distinct operation");
         foreach (var item in employees)
         {
            Console.WriteLine(item.Name + " : " + item.Age + " : " + item.Address);
         }
         Console.ReadLine();
      }
   }
Output
How To Remove Duplicate Items In A List Using IEqualityComparer

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input