【发布时间】:2013-02-07 19:08:35
【问题描述】:
我有一个 HashSet。是否有一种方法可以利用 IEqualityComparer 检索您传入的对象的项目,该对象将满足 IEqualityComparer 中定义的 equals 方法?
这可能解释得更清楚了。
public class Program
{
public static void Main()
{
HashSet<Class1> set = new HashSet<Class1>(new Class1Comparer());
set.Add( new Class1() { MyProperty1PK = 1, MyProperty2 = 1});
set.Add( new Class1() { MyProperty1PK = 2, MyProperty2 = 2});
if (set.Contains(new Class1() { MyProperty1PK = 1 }))
Console.WriteLine("Contains the object");
//is there a better way of doing this, using the comparer?
// it clearly needs to use the comparer to determine if it's in the hash set.
Class1 variable = set.Where(e => e.MyProperty1PK == 1).FirstOrDefault();
if(variable != null)
Console.WriteLine("Contains the object");
}
}
class Class1
{
public int MyProperty1PK { get; set; }
public int MyProperty2 { get; set; }
}
class Class1Comparer : IEqualityComparer<Class1>
{
public bool Equals(Class1 x, Class1 y)
{
return x.MyProperty1PK == y.MyProperty1PK;
}
public int GetHashCode(Class1 obj)
{
return obj.MyProperty1PK;
}
}
【问题讨论】:
-
您的 GetHashCode 可能应该返回属性的哈希码,而不是属性本身
-
@pstrjds True - 虽然在这种情况下(因为它是一个 int),这仍然可以工作。
-
@ReedCopsey - 我更多的是从“最佳实践”的角度来看待它。
-
接下来我将研究实现 IEqualityComparer 的最佳实践。 :-)
标签: c# collections hashset