【问题标题】:Select all of a particular item from a HashSet从 HashSet 中选择所有特定项目
【发布时间】:2014-11-21 15:03:00
【问题描述】:

我有一个名为 User 的简单类:

public class User
{
    public int ID { get; set; }
    public int MI { get; set; }

    public User(int id, int mi)
    {
        ID = ID;
        MI = mi;
    }
}

稍后,我有一个用户的 HashSet,我想从中获取 ID 并分配给 HashSet 中的一个,如下所示:

    HashSet<Users> _users = new HashSet<>();
    //code where several User objects are assigned to _users
    HashSet<int> _usersIDs = new HashSet<int>();
    _usersIDs = _users.Select("ID")

但这不起作用,我怎样才能成功地将_users中的所有int ID分配给一个新的HashSet?

【问题讨论】:

  • HashSet&lt;int&gt; _usersIDs = new HashSet&lt;int&gt;(_users.Select(x=&gt; x.ID));
  • 值得注意的是,您的所有ID 对所有用户都是相同的,因为您在构造函数中分配的是ID = ID 而不是ID = id

标签: c# data-structures hashset


【解决方案1】:

你可以这样做:

HashSet<int> _usersIDs = new HashSet<int>(_users.Select(user=> user.ID));

但是如果你打算在HashSet&lt;T&gt; 中使用User 类,你应该为GetHashCode 覆盖它并且可能 Eqauls 以及像:

public class User
{
    protected bool Equals(User other)
    {
        return ID == other.ID && MI == other.MI;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((User) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (ID*397) ^ MI;
        }
    }

    public int ID { get; set; }
    public int MI { get; set; }

    public User(int id, int mi)
    {
        ID = id; //based on @Jonesy comment
        MI = mi;
    }
}

【讨论】:

  • 哈希码真的应该依赖IDMI吗?它们是可变属性,如果在将项目添加到哈希集中后它们发生变化,用户将突然进入错误的存储桶并变得无法检索。
  • 换句话说,如果您要将User 的实例放入哈希集或将它们用作字典中的键,那么使类型不可变可能是个好主意。跨度>
  • "也可能是 Equals" ...实际上,文档说如果你覆盖一个,你应该覆盖另一个。我记得,Visual Studio(或者可能是编译器)强制要求这样做。 msdn.microsoft.com/en-us/library/…
  • 这个,或者不要使用HashSet,因为没有不可变的属性。我的意思是,没有覆盖 GetHashCode 的 HashSet 是没有用的。更多关于...stackoverflow.com/a/19721436/961113
  • @JimMischel,编译器没有限制。 Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.。这就是为什么我说“可能”。如果只实现其中任何一个,则不会出现任何错误,因为将使用基类中的virtual 方法。但它们将无法正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多