在 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();
}
}
關鍵注意事項
唯一性保證
HashSet
會自動去重,重復添加相同地址不會有副作用:
whiteList.Add("192.168.1.100"); // 已存在時自動忽略
大小寫敏感
地址字符串區分大小寫,建議統一使用小寫:
whiteList.Add("192.168.1.100".ToLower()); // 推薦統一格式
IP格式驗證
建議添加前驗證地址格式有效性:
if (IPAddress.TryParse("192.168.1.100", out _))
{
whiteList.Add("192.168.1.100");
}
性能優勢
HashSet
的添加(Add
)和查找(Contains
)操作時間復雜度為 O(1),適合高頻操作。
通過上述方法,您可以靈活地動態管理白名單地址。如果需要持久化存儲,建議將白名單保存到配置文件或數據庫中,并在程序啟動時加載到 HashSet
中。
該文章在 2025/3/14 22:27:28 編輯過