C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# HashSet<T>

C# HashSet 类可用于存储、删除或查看元素。它不存储重复的元素。如果您必须只存储唯一元素,建议使用 HashSet 类。它位于 System.Collections.Generic 命名空间中。

C# HashSet<T> 示例

让我们看一个通用 HashSet<T> 类的示例,该类使用 Add() 方法存储元素并使用 for-each 循环迭代元素。

例子 (Example)

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

让我们看另一个使用 Collection 初始化器存储元素的通用 HashSet<T> 类的示例。

例子 (Example)

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# List<T> 列表 下一主题 C# SortedSet<T> 排序集
  • 使用社交账号登录,本站支持
全部评论(0)