c#,EqualityComparer,Equality,Comparer

Erhan 8/16/2016 0

This Code Shows How to Use EqualityComparer

C#
 public class Customer
{
  public string LastName;
  public string FirstName;

  public Customer (string last, string first)
  {
    LastName = last;
    FirstName = first;
  }
}

public class LastFirstEqComparer : EqualityComparer <Customer>
{
  public override bool Equals (Customer x, Customer y)
  {
    return x.LastName == y.LastName && x.FirstName == y.FirstName;
  }

  public override int GetHashCode (Customer obj)
  {
    return (obj.LastName   ";"   obj.FirstName).GetHashCode();
  }
}

static void Main()
{
  Customer c1 = new Customer ("Bloggs", "Joe");
  Customer c2 = new Customer ("Bloggs", "Joe");

  // Because we’ve not overridden object.Equals, normal reference
  // type equality semantics apply:

  Console.WriteLine (c1 == c2);               // false
  Console.WriteLine (c1.Equals (c2));         // false

  Dictionary<Customer, string> d = new Dictionary<Customer, string>();
  d [c1] = "Joe";
  Console.WriteLine (d.ContainsKey (c2));         // false

  // Now with the custom equality comparer:
  
  LastFirstEqComparer eq = new LastFirstEqComparer();
  d = new Dictionary<Customer, string> (eq);
  d [c1] = "Joe";
  Console.WriteLine (d.ContainsKey (c2));         // true
} 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments