Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Equality Comparer for comparing objects based on members
using System;
using System.Collections.Generic;
using System.Linq;
// SO Link 1 : https://stackoverflow.com/a/263416/302248
// SO Link 2 : https://stackoverflow.com/q/45601078/302248
namespace ComparerGetHashCode
{
public class NumberClass
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
}
public class NumberComparer : IEqualityComparer<NumberClass>
{
public bool Equals(NumberClass x, NumberClass y)
{
if (x.A == y.A && x.B == y.B)
return true;
else
return false;
}
public int GetHashCode(NumberClass obj)
{
unchecked
{
int hash = 17;
if (obj != null)
{
hash = hash * 23 + obj.A.GetHashCode();
hash = hash * 23 + obj.B.GetHashCode();
}
return 0;
}
}
// Alternate method I.
public int GetHashCode(NumberClass obj)
{
unchecked
{
int hash = (int)2166136261;
hash = (hash * 16777619) ^ obj.A.GetHashCode();
hash = (hash * 16777619) ^ obj.B.GetHashCode();
return hash;
}
}
// Alternate method II.
public int GetHashCode(NumberClass obj)
{
unchecked
{
return new { obj.A, obj.B }.GetHashCode();
}
}
}
class EqualityComparer
{
static void Main(string[] args)
{
List<NumberClass> list = new List<NumberClass>();
list.Add(new NumberClass { A = 1, B = 2, C = 3 });
list.Add(new NumberClass { A = 1, B = 22, C = 33 });
list.Add(new NumberClass { A = 1, B = 22, C = 333 });
var distinct = list.Distinct(new NumberComparer());
ObjectDumper.Write(distinct);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.