使用HashSet C#选择项目

pri*_*ehl 2 c# collections hashset

我有一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 7

如果要基于单个属性检索项目,可能需要使用Dictionary<T,U>而不是哈希集.然后,您可以将项目MyProperty1PK作为键放在字典中.

您的查询变得简单:

Class1 variable;
if (!dictionary.TryGetValue(1, out variable)
{
  // class wasn't in dictionary
}
Run Code Online (Sandbox Code Playgroud)

鉴于您已经使用仅使用此值作为唯一性标准的比较器进行存储,因此仅使用该属性作为字典中的键确实没有缺点.