C#HashSet<T>类

C#HashSet<T>类 首页 / C#入门教程 / C#HashSet<T>类

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

C# HashSet<T> example

让无涯教程看一个泛型HashSet<T>类的示例,该类使用add()方法存储元素,并使用for-each循环迭代元素。

using System;
using System.Collections.Generic;

public class HashSetExample
{
    public static void Main(string[] args)
    {
        //创建一组字符串
        var names = new HashSet();
        names.Add("Sonoo");
        names.Add("Ankit");
        names.Add("Peter");
        names.Add("Irfan");
        names.Add("Ankit");//不会添加
        
        //使用 foreach 循环迭代 HashSet 元素
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-hashset.html

来源:LearnFk无涯教程网

Sonoo
Ankit
Peter
Irfan

C# HashSet<T> example 2

让无涯教程看一下使用集合初始值设定项存储元素的泛型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(){"Sonoo", "Ankit", "Peter", "Irfan"};
        
        //使用 foreach 循环迭代 HashSet 元素
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-hashset.html

来源:LearnFk无涯教程网

Sonoo
Ankit
Peter
Irfan

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

重学TypeScript -〔周爱民〕

零基础学Python(2023版) -〔尹会生〕

手把手带你搭建秒杀系统 -〔佘志东〕

成为AI产品经理 -〔刘海丰〕

实用密码学 -〔范学雷〕

职场求生攻略 -〔臧萌〕

Serverless入门课 -〔蒲松洋(秦粤)〕

从0开始学游戏开发 -〔蔡能〕

深入浅出区块链 -〔陈浩〕

好记忆不如烂笔头。留下您的足迹吧 :)