C# HashSet<T>
C# HashSet<T>
C# HashSet 类可用于存储、删除或查看元素。它不存储重复的元素。如果您只需要存储唯一元素,建议使用 HashSet 类。它位于 System.Collections.Generic 命名空间中。
C# HashSet
示例
让我们看一个存储元素的通用 HashSet
类的示例使用 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);
}
}
}
输出:
C# HashSet
示例 2
让我们看另一个使用集合初始值设定项存储元素的通用 HashSet
类示例。
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);
}
}
}
输出: