从HashSet中选择所有特定项

时间:2014-11-21 15:03:01

标签: c# data-structures hashset

我有一个名为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用户,我希望从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?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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

但是,如果您要在GetHashCode 中使用User HashSet<T>,那么您应该覆盖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; } } 像:

{{1}}