linq - Implementing IEqualityComparer<T> on an object with two properties in C# -
i have case need grab bunch of items on distinct, source collection of objects 2 properties, this:
public class skillrequirement { public string skill { get; set; } public string requirement { get; set; } } i try collection follows:
skillrequirementcomparer scom = new skillrequirementcomparer(); var distinct_list = source.distinct(scom); i tried implement iequalitycomparer<t> this, fell stumped @ gethashcode() method.
the class comparer:
public class skillrequirementcomparer : iequalitycomparer<skillrequirement> { public bool equals(skillrequirement x, skillrequirement y) { if (x.skill.equals(y.skill) && x.requirement.equals(y.requirement)) { return true; } else { return false; } } public int gethashcode(skillrequirement obj) { //????? } } normally use gethashcode() on property, because comparing on 2 properties, i'm bit @ loss of do. doing wrong, or missing obvious?
you can implement gethashcode in following way:
public int gethashcode(skillrequirement obj) { unchecked { int hash = 17; hash = hash * 23 + obj.skill.gethashcode(); hash = hash * 23 + obj.requirement.gethashcode(); return hash; } } originally j.skeet
if properties can null should avoid nullreferenceexception, e.g.:
int hash = 17; hash = hash * 23 + (obj.skill ?? "").gethashcode(); hash = hash * 23 + (obj.requirement ?? "").gethashcode(); return hash;
Comments
Post a Comment