Created
August 9, 2017 22:45
-
-
Save sachintha81/651305704811d03a77072befc7ca0937 to your computer and use it in GitHub Desktop.
Equality Comparer for comparing objects based on members
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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