HashSet是唯一元素的无序集合。它位于System.Collections.Generic命名空间下。它用于我们要防止将重复项插入到集合中的情况。就性能而言,与列表相比更好。您可以通过在创建HashSet对象的同时将集合作为参数传递来从另一个集合创建HashSet。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to Create HashSet
// from another collection
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 10 in HashSet mySet
for (int i = 0; i < 5; i++) {
mySet.Add(i * 2);
}
// Creating new HashSet mySet_new from already
// Created HashSet mySet
HashSet mySet_new = new HashSet(mySet);
Console.WriteLine("The elements in newly created HashSet are : ");
// Displaying the elements of newly created HashSet
foreach(int i in mySet_new)
{
Console.WriteLine(i);
}
}
}
输出:
The elements in newly created HashSet are :
0
2
4
6
8
范例2:
// C# code to Create HashSet
// from another collection
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 into HashSet mySet
mySet.Add("Delhi");
mySet.Add("Noida");
mySet.Add("Chandigarh");
mySet.Add("New York");
mySet.Add("Bangalore");
// Creating new HashSet mySet_new from already
// Created HashSet mySet
HashSet mySet_new = new HashSet(mySet);
Console.WriteLine("The elements in newly created HashSet are : ");
// Displaying the elements of newly created HashSet
foreach(string i in mySet_new)
{
Console.WriteLine(i);
}
}
}
输出:
The elements in newly created HashSet are :
Delhi
Noida
Chandigarh
New York
Bangalore