【问题标题】:Selecting Items using a HashSet C#使用 HashSet C# 选择项目
【发布时间】: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


【解决方案1】:

如果您想检索基于单个属性的项目,您可能需要使用Dictionary&lt;T,U&gt; 而不是哈希集。然后,您可以使用 MyProperty1PK 作为键将项目放入字典中。

你的查询就变得简单了:

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

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

【讨论】:

  • 我同意,但是有一个值字典似乎很奇怪......存储在键中,然后没有存储在 value 属性中。值得考虑这样的事情吗? _set.Intersect(new List { item }).FirstOrDefault()
  • 看起来不是,因为这只是 IEnumerable 上的一个扩展方法...感谢您的帮助。
  • @priehl 我会使用Dictionary&lt;int, Class1&gt; - 将道具存储在键中,将类本身存储在值中......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多