HashSet是唯一元素的无序集合。它位于System.Collections.Generic命名空间下。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。哈希集
句法:
mySet.Clear();
在这里, mySet是HashSet的名称。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to remove all elements from HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of integers
HashSet mySet = new HashSet();
// Inserting even numbers less than
// equal to 20 in HashSet mySet1
for (int i = 0; i < 10; i++) {
mySet.Add(i * 2);
}
// Displaying the number of elements in HashSet
Console.WriteLine(mySet.Count);
// Removing all the elements from HashSet
mySet.Clear();
// Displaying the number of elements in HashSet
// after removing all the elements from it
Console.WriteLine(mySet.Count);
}
}
输出:
10
0
范例2:
// C# code to remove all elements from HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of strings
HashSet mySet = new HashSet();
// Inserting elements in HashSet
mySet.Add("Geeks");
mySet.Add("and");
mySet.Add("GeeksforGeeks");
mySet.Add("are");
mySet.Add("the");
mySet.Add("best");
// Displaying the number of elements in HashSet
Console.WriteLine(mySet.Count);
// Removing all the elements from HashSet
mySet.Clear();
// Displaying the number of elements in HashSet
// after removing all the elements from it
Console.WriteLine(mySet.Count);
// Inserting elements in HashSet
mySet.Add("Join");
mySet.Add("Geeks");
mySet.Add("Classes");
// Displaying the number of elements in HashSet
Console.WriteLine(mySet.Count);
}
}
输出:
6
0
3
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.hashset-1.clear?view=netframework-4.7.2