.NET中仅允许唯一项的集合? [英] Collection that allows only unique items in .NET?
问题描述
C#中是否存在一个集合,不允许您向其中添加重复项?例如,对于愚蠢的类
Is there a collection in C# that will not let you add duplicate items to it? For example, with the silly class of
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);
}
}
以下代码(显然)将引发异常:
The following code will (obviously) throw an exception:
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>
可以做到这一点,但是看完文档后,类似乎只是一个设置实现( go )。 / p>
But is there a class that will similarly guarantee uniqueness, but without KeyValuePairs? I thought HashSet<T>
would do that, but having read the docs it seems that class is just a set implementation (go figure).
推荐答案
HashSet< T>
是您要的内容。从 MSDN (强调):
HashSet<T>
is what you're looking for. From MSDN (emphasis added):
HashSet< T>
类提供高性能的集合操作。集合是不包含重复元素且其元素没有特定顺序的集合。
The
HashSet<T>
class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
请注意, HashSet< T> .Add(T item)
方法返回 bool
- true
(如果该项目已添加到集合中); false
(如果该项目已经存在)。
Note that the HashSet<T>.Add(T item)
method returns a bool
-- true
if the item was added to the collection; false
if the item was already present.
这篇关于.NET中仅允许唯一项的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!