Reputation: 1384
I have a simple class called 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<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?
Upvotes: 0
Views: 2779
Reputation: 223247
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:
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;
}
}
Upvotes: 1