[英]Select all of a particular item from a HashSet
I have a simple class called User : 我有一个名为User的简单类:
public class User
{
public int ID { get; set; }
public int MI { get; set; }
public User(int id, int mi)
{
ID = ID;
MI = mi;
}
}
And later on, I have a HashSet of Users that I want to get the ID's from and assign to a in HashSet as follows : 然后,我有一个用户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")
But this doesn't work, how can I successfully assigned all of the int ID's in _users to a new HashSet? 但这不起作用,如何将_users中的所有int ID成功分配给新的HashSet?
You can do: 你可以做:
HashSet<int> _usersIDs = new HashSet<int>(_users.Select(user=> user.ID));
But you should override GetHashCode
for your User
class if you are going to use it in a HashSet<T>
and possibily Eqauls
as well like: 但是,如果要在HashSet<T>
和可能的 Eqauls
使用它,则应重写User
类的GetHashCode
,例如:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.