实现IEqualityComparer< T>c#中有两个属性的对象
本文关键字:两个 属性 对象 IEqualityComparer 实现 | 更新日期: 2023-09-27 18:14:50
我有一个案例,我需要抓取一堆不同的项目,但我的源代码是一个具有两个属性的对象集合,像这样:
public class SkillRequirement
{
public string Skill { get; set; }
public string Requirement { get; set; }
}
我尝试得到一个集合如下:
SkillRequirementComparer sCom = new SkillRequirementComparer();
var distinct_list = source.Distinct(sCom);
我试图为此实现IEqualityComparer<T>
,但我在GetHashCode()
方法上遇到了困难。
比较器的类:
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()
,但因为我比较两个属性,我有点不知所措。是我做错了什么,还是遗漏了什么很明显的东西?
您可以通过以下方式实现GetHashCode
:
public int GetHashCode(SkillRequirement obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + obj.Skill.GetHashCode();
hash = hash * 23 + obj.Requirement.GetHashCode();
return hash;
}
}
源自J.Skeet
如果属性可以是null
,你应该避免NullReferenceException
,例如:
int hash = 17;
hash = hash * 23 + (obj.Skill ?? "").GetHashCode();
hash = hash * 23 + (obj.Requirement ?? "").GetHashCode();
return hash;
我想链接下面的堆栈溢出帖子,虽然这个问题已经回答了…
GetHashCode -
当Equals方法被重写时,为什么重写GetHashCode很重要?
同样,在上面的回答中,Tim Schmelter说the properties can be null you should avoid a NullReferenceException
int hash = 17;
hash = hash * 23 + (obj.Skill ?? "").GetHashCode();
hash = hash * 23 + (obj.Requirement ?? "").GetHashCode();
return hash;
iqualitycomparer -
- 使用IEqualityComparer和Equals/GethashCode Override有什么区别 GetHashCode在。net中的IEqualityComparer中的作用是什么?c#中如何以及何时使用IEqualityComparer
IEquatable - IEquatable和仅仅重写Object.Equals()之间的区别是什么?
Equals -重载Equals()指南
class TwoDPoint : System.Object
{
public readonly int x, y;
public TwoDPoint(int x, int y) //constructor
{
this.x = x;
this.y = y;
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
//return x ^ y;
}
}