C# 中操作 HashSet<string> 类型增加或删除里面的项目
|
admin
2025年3月13日 12:44
本文热度 194
|
在 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. 批量添加
string[] newIps = { "172.16.0.1", "172.16.0.2" };
foreach (string ip in newIps)
{
whiteList.Add(ip);
}
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");
if (removed)
{
Console.WriteLine("已移除指定IP");
}
2. 批量移除
string[] removeIps = { "192.168.1.100", "203.0.113.5" };
foreach (string ip in removeIps)
{
whiteList.Remove(ip);
}
HashSet<string> ipsToRemove = new HashSet<string> { "198.51.100.10", "172.16.0.1" };
whiteList.ExceptWith(ipsToRemove);
三、清空白名单
whiteList.Clear();
Console.WriteLine($"清空后白名单数量:{whiteList.Count}");
四、完整操作示例
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();
}
}
关键注意事项
唯一性保证
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/13 12:44:21 编辑过