欧美成人精品手机在线观看_69视频国产_动漫精品第一页_日韩中文字幕网 - 日本欧美一区二区

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C# 中操作 HashSet<string> 類型增加或刪除里面的項目

admin
2025年3月13日 12:44 本文熱度 562

在 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);
}

//判斷是否有內容
if (whiteList.Count > 0)
{
Console.WriteLine("whiteList 中有內容。");
}
else
{
Console.WriteLine("whiteList 是空的。");
}

// 清空操作
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/14 22:27:28 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved