HashSet <t>快速检查T.identity </t>是否存在身份

时间:2013-11-22 11:32:10

标签: c# linq containers hashset

我有一个名为Feature的实体,其中包含一个名为FeatureIdentity的值标识。

我有这些实体的列表,我想快速确定身份是否已经存在。

踢球者是我需要能够通过FeatureIdentity进行比较而不是Feature,列表上的Contains过程是根据提供的T参数进行检查。

所以我正在做代码:

public class SomeClass
{
    HashSet<Feature> features = new HashSet<Feature>();

    public void SetRequirement(FeatureIdentity feature, FeatureIdentity requires)
    {
        if (ContainsFeature(feature) == false || ContainsFeature(requires) == false)
        {
            // throw
        }
        this.requirements.Add(feature, requires);
    }

    bool ContainsFeature(FeatureIdentity identity)
    {
        return this.features.Where(x => x.Id.Equals(identity)).Count() > 0;
    }
}

Linq是否对此进行了优化,或者这是否存在检查项目是否存在的正确最佳方式?

public class Feature
{
   public Feature(FeatureIdentity id, string name)
   {
      this.id = id;
      this.name = name;
   }

   FeatureIdentity id;
   string name;

   FeatureIdentity Id
   {
      get { return this.id; }
   }
}

public class FeatureIdentity : IEquatable<FeatureIdentity>
{
    private readonly string sku;

    public FeatureIdentity(string sku)
    {
        this.sku = sku;
    }

    public bool Equals(FeatureIdentity other)
    {
        return this.sku == other.sku;
    }

    public string Sku
    {
        get { return this.sku; }
    }

    public override int GetHashCode()
    {
        return this.sku.GetHashCode();
    }
}

1 个答案:

答案 0 :(得分:2)

使用ctor public HashSet()HashSet<Feature>使用EqualityComparer<Feature>.Default作为默认的Comparer。

如果您使用HashSet<Feature>,,则应实施IEquatable<Feature>并覆盖GetHashCode

public class Feature: IEquatable<Feature>
{
    public bool Equals(Feature other)
    {
        return this.id.Equals(other.id);
    }

    public override int GetHashCode()
    {
        return this.id.GetHashCode();
    }
}

然后你可以尝试以下解决方法,它可以从堆中获取临时对象。

bool ContainsFeature(FeatureIdentity identity)
{
    return this.features.Contain(new Feature(identity, null));
}