2014-11-21 34 views
0

我有一個簡單的類稱爲用戶選擇所有特定項目的:從一個HashSet

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") 

但是,這並不工作,我怎樣才能成功地分配所有的INT ID在_users提高到一個新的HashSet?

+2

' HashSet _usersIDs = new HashSet (_users.Select(x => x.ID));' – 2014-11-21 15:05:39

+4

值得注意的是,所有'ID'都是ar e對於所有用戶來說都是一樣的,因爲你在構造函數中分配'ID = ID'而不是'ID = id' – Jonesopolis 2014-11-21 15:09:56

回答

1

你可以這樣做:

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

但你應該重寫GetHashCodeUser類,如果你要在一個HashSet<T>和possibilyEqauls使用它,以及像:

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

散列代碼是否應該真的依賴於'ID'和'MI'?它們是可變屬性,如果它們在項目被添加到哈希集合後發生更改,則用戶將突然陷入錯誤的桶中,並且無法恢復。 – dcastro 2014-11-21 15:13:29

+0

換句話說,如果你要刪除'User'的實例來介紹一個散列集或者將它們用作字典中的鍵,那麼使這個類型不可變是個好主意。 – dcastro 2014-11-21 15:14:50

+0

「並且可能也是Equals」......實際上,文檔說如果你重寫一個,你應該重寫另一個。我記得,Visual Studio(或者編譯器)使它成爲強制性的。 http://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx – 2014-11-21 15:16:52