哈希集有一个Contains https://learn.microsoft.com/nl-nl/dotnet/api/system.collections.generic.hashset-1.contains方法允许您检查某个值是否在集合中。
除此之外HashSet<T>
实施ISet<T> https://learn.microsoft.com/nl-nl/dotnet/api/system.collections.generic.iset-1接口,因此提供了许多处理集合的方法,例如并集、交集以及确定一组值是否是集合的(正确)超集或子集。
HashSet<int> intTest = new HashSet<int>()
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
bool has4 = intTest.Contains(4); // Returns true
bool has11 = intTest.Contains(11); // Returns false
bool result = intTest.IsSupersetOf(new []{ 4, 6, 7 }); // Returns true
By the way, did you know about the collection initializer https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers syntax?
你也可以foreach
在集合上获取它包含的每个元素(以未指定的顺序):
foreach(int value in intTest)
{
// Do something with value.
}
或者将其转换为数组或可变列表(也以未指定的顺序):
int[] arr = intTest.ToArray();
List<int> lst = intTest.ToList();