实现的IEqualityComparer< T>在C#两个属性的对象上 [英] Implementing IEqualityComparer<T> on an object with two properties in C#
问题描述
我有,我需要抢了一堆对不同项目的情况,但我的来源是对象的集合,具有两个属性,就像这样:
I have a case where I need to grab a bunch of items on distinct, but my source is a collection of objects with two properties, like this:
public class SkillRequirement
{
public string Skill { get; set; }
public string Requirement { get; set; }
}
我试图让一个集合如下:
I try to get a collection as follows:
SkillRequirementComparer sCom = new SkillRequirementComparer();
var distinct_list = source.Distinct(sCom);
我试图实施的IEqualityComparer< T>
对于这一点,但我摔倒在的GetHashCode()
方法难倒
I tried to implement an IEqualityComparer<T>
for this, but I fell stumped at the GetHashCode()
method.
有关比较器类:
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)
{
//?????
}
}
通常我只会用 GetHashCode的()
上的属性,但因为我在比较两个属性,我有点在做什么损失。难道我做错什么,或者失去了一些东西真的很明显?
Normally I would just use GetHashCode()
on a property, but because I am comparing on two properties, I'm a bit at a loss of what to do. Am I doing anything wrong, or missing something really obvious?
推荐答案
您可以实施的GetHashCode
以下列方式:
You can implement GetHashCode
in the 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
originally from J.Skeet
如果该属性可以是空
你应该避免的NullReferenceException
,例如:
If the properties can be null
you should avoid a NullReferenceException
, e.g.:
int hash = 17;
hash = hash * 23 + (obj.Skill ?? "").GetHashCode();
hash = hash * 23 + (obj.Requirement ?? "").GetHashCode();
return hash;
这篇关于实现的IEqualityComparer< T>在C#两个属性的对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!