在C#中是否有一個集合不會讓您向其中添加重複的項目?例如,傻類的僅允許.NET中唯一項目的集合?
public class Customer {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public override int GetHashCode() {
return (FirstName + LastName + Address).GetHashCode();
}
public override bool Equals(object obj) {
Customer C = obj as Customer;
return C != null && String.Equals(this.FirstName, C.FirstName) && String.Equals(this.LastName, C.LastName) && String.Equals(this.Address, C.Address);
}
}
將下面的代碼(顯然)拋出一個異常:
Customer Adam = new Customer { Address = "A", FirstName = "Adam", LastName = "" };
Customer AdamDup = new Customer { Address = "A", FirstName = "Adam", LastName = "" };
Dictionary<Customer, bool> CustomerHash = new Dictionary<Customer, bool>();
CustomerHash.Add(Adam, true);
CustomerHash.Add(AdamDup, true);
但是有沒有將同樣保證唯一性一類,但沒有KeyValuePairs?我認爲HashSet<T>
會這樣做,但閱讀文檔看來,類只是一個集合實現(去圖)。
我不明白你的問題'HashSet'。 MSDN說:「HashSet 類提供了高性能的集合操作,一個集合是一個不包含重複元素的集合,其元素沒有特定的順序。」 –
2011-03-01 17:11:20
你能解釋一下爲什麼'HashSet'不夠? –
JaredPar
2011-03-01 17:11:46
@ mootinator:'Dictionary'class *不保證任何順序。 –
LukeH
2011-03-01 17:23:15