【C#集合HashSet】C#HashSet类可用于存储,删除或查看元素。它不存储重复的元素。如果你只需要存储唯一元素,则建议使用HashSet类。在System.Collections.Generic命名空间中找到它。
C#HashSet <
T>
示例
让我们看一个通用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
C#HashSet < T> 示例2
让我们看看使用HashSet < T> 类的另一个示例,该类使用Collection初始化程序存储元素。
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
推荐阅读
- C#集合SortedSet
- C#列表List
- C#集合
- C#系统io(System.IO)
- C#反序列化
- C#序列化
- C# DirectoryInfo用法
- C# FileInfo用法
- C# StringReader用法