C# HashSet 类可用于存储、删除或查看元素。它不存储重复的元素。如果您必须只存储唯一元素,建议使用 HashSet 类。它位于 System.Collections.Generic 命名空间中。
让我们看一个通用 HashSet<T> 类的示例,该类使用 Add() 方法存储元素并使用 for-each 循环迭代元素。
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet<string>();
names.Add("Sonoo");
names.Add("Ankit");
names.Add("Peter");
names.Add("Irfan");
names.Add("Ankit");//will not be added
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}输出:
Sonoo Ankit Peter Irfan
让我们看另一个使用 Collection 初始化器存储元素的通用 HashSet<T> 类的示例。
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main(string[] args)
{
// Create a set of strings
var names = new HashSet<string>(){"Sonoo", "Ankit", "Peter", "Irfan"};
// Iterate HashSet elements using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
输出:
Sonoo Ankit Peter Irfan