LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 中操作 HashSet<string> 类型增加或删除里面的项目

admin
2025年3月13日 12:44 本文热度 112

在 C# 中操作 HashSet<string> 类型的白名单非常简单,以下是具体操作方法:

HashSet<string> whiteList = new HashSet<string>

{

    "192.168.1.100",

    "10.0.0.5"

};

一、添加白名单地址

1、逐个添加

whiteList.Add("192.168.1.101");  // 添加单个地址

whiteList.Add("10.0.0.6");

2. 批量添加

// 方法1:使用 Add 方法遍历添加

string[] newIps = { "172.16.0.1", "172.16.0.2" };

foreach (string ip in newIps)

{

    whiteList.Add(ip);

}


// 方法2:使用 UnionWith 合并集合

HashSet<string> additionalIps = new HashSet<string> { "203.0.113.5", "198.51.100.10" };

whiteList.UnionWith(additionalIps);  // 自动去重合并


二、移除白名单地址

1、移除单个地址

bool removed = whiteList.Remove("10.0.0.5");  // 返回 true 表示成功

if (removed) 

{

    Console.WriteLine("已移除指定IP");

}

2. 批量移除

// 方法1:遍历移除

string[] removeIps = { "192.168.1.100", "203.0.113.5" };

foreach (string ip in removeIps)

{

    whiteList.Remove(ip);

}


// 方法2:使用 ExceptWith 差集操作

HashSet<string> ipsToRemove = new HashSet<string> { "198.51.100.10", "172.16.0.1" };

whiteList.ExceptWith(ipsToRemove);  // 从白名单中排除指定集合


三、清空白名单

whiteList.Clear();  // 移除所有元素

Console.WriteLine($"清空后白名单数量:{whiteList.Count}");  // 输出 0


四、完整操作示例

using System;

using System.Collections.Generic;


class Program

{

    static void Main()

    {

        // 初始化白名单

        HashSet<string> whiteList = new HashSet<string>

        {

            "192.168.1.100",

            "10.0.0.5"

        };


        // 添加操作

        whiteList.Add("172.16.0.3");

        whiteList.UnionWith(new[] { "203.0.113.4", "203.0.113.5" });


        // 移除操作

        whiteList.Remove("10.0.0.5");

        whiteList.ExceptWith(new[] { "203.0.113.4" });


        // 输出当前白名单

        Console.WriteLine("当前白名单:");

        foreach (string ip in whiteList)

        {

            Console.WriteLine(ip);

        }


        // 清空操作

        whiteList.Clear();

    }

}


关键注意事项

  1. 唯一性保证
    HashSet 会自动去重,重复添加相同地址不会有副作用:

whiteList.Add("192.168.1.100");  // 已存在时自动忽略
  1. 大小写敏感
    地址字符串区分大小写,建议统一使用小写:

whiteList.Add("192.168.1.100".ToLower());  // 推荐统一格式
  1. IP格式验证
    建议添加前验证地址格式有效性:

if (IPAddress.TryParse("192.168.1.100", out _))

{

    whiteList.Add("192.168.1.100");

}

  1. 性能优势
    HashSet 的添加(Add)和查找(Contains)操作时间复杂度为 O(1),适合高频操作。


通过上述方法,您可以灵活地动态管理白名单地址。如果需要持久化存储,建议将白名单保存到配置文件或数据库中,并在程序启动时加载到 HashSet 中。


该文章在 2025/3/13 12:44:21 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved