EqualityComparer(T) Class provides a base class for implementations of the IEqualityComparer generic interface.
using System;
using System.Collections.Generic;
class Program
{
static Dictionary<Rectangle, String> boxes;
static void Main(string[] args)
{
RectangleSameDimensions boxDim = new RectangleSameDimensions();
boxes = new Dictionary<Rectangle, string>(boxDim);
Rectangle redBox = new Rectangle(8, 4);
Rectangle greenBox = new Rectangle(8, 6);
Rectangle blueBox = new Rectangle(8, 4);
Rectangle yellowBox = new Rectangle(8, 8);
AddBox(redBox, "red");
AddBox(greenBox, "green");
AddBox(blueBox, "blue");
AddBox(yellowBox, "yellow");
Console.WriteLine();
Console.WriteLine("Boxes equality by volume:");
BoxSameVolume boxVolume = new BoxSameVolume();
boxes = new Dictionary<Rectangle, string>(boxVolume);
Rectangle pinkBox = new Rectangle(8, 4);
Rectangle orangeBox = new Rectangle(8, 6);
Rectangle purpleBox = new Rectangle(4, 8);
Rectangle brownBox = new Rectangle(8, 8);
AddBox(pinkBox, "pink");
AddBox(orangeBox, "orange");
AddBox(purpleBox, "purple");
AddBox(brownBox, "brown");
}
public static void AddBox(Rectangle bx, string name)
{
try
{
boxes.Add(bx, name);
Console.WriteLine("Added {0}, Count = {1}, HashCode = {2}",
name, boxes.Count.ToString(), bx.GetHashCode());
}
catch (ArgumentException)
{
Console.WriteLine("A box equal to {0} is already in the collection.", name);
}
}
}
public class Rectangle
{
public Rectangle(int h, int l)
{
this.Height = h;
this.Length = l;
}
public int Height { get; set; }
public int Length { get; set; }
}
class RectangleSameDimensions : EqualityComparer<Rectangle>
{
public override bool Equals(Rectangle b1, Rectangle b2)
{
if (b1.Height == b2.Height & b1.Length == b2.Length)
{
return true;
}
else
{
return false;
}
}
public override int GetHashCode(Rectangle bx)
{
int hCode = bx.Height ^ bx.Length;
return hCode.GetHashCode();
}
}
class BoxSameVolume : EqualityComparer<Rectangle>
{
public override bool Equals(Rectangle b1, Rectangle b2)
{
if (b1.Height * b1.Length ==
b2.Height * b2.Length)
{
return true;
}
else
{
return false;
}
}
public override int GetHashCode(Rectangle bx)
{
int hCode = bx.Height ^ bx.Length;
return hCode.GetHashCode();
}
}
Related examples in the same category