gpt4 book ai didi

c# - LINQ 中用于遍历 HashSet 的聪明替代方案

转载 作者:太空狗 更新时间:2023-10-30 00:09:17 26 4
gpt4 key购买 nike

我在 HashSet<string> 中有一个我正在使用的 URL 的白名单.我正在尝试查找 url 是否以白名单中的任何一项开始(必须是这样)。

编辑:前面的示例有点误导并且有错字 - 我已经有一个像 yahoo.com 这样的基本 url,白名单只是路径。

HashSet<string> whiteList = new HashSet<string>();

string path = "/sport/baseball/";
bool validUrl = false;

foreach (string item in whiteList)
{
if (path.StartsWith(item))
{
validUrl = true;
break;
}
}

是否有更优雅的方式使用 LINQ(对象)执行此查找?该列表并不大,因此性能不是问题。

最佳答案

bool validUrl = whiteList.Any(item => linkUrl.StartsWith(item));

顺便说一句,一般来说,哈希表不是解决这类问题的好数据结构(你没有 key ,而是根据函数匹配 key ),因为你必须枚举整个表一直。您可以使用简单的 List<string>改为持有元素,你会获得更好的表现。

关于c# - LINQ 中用于遍历 HashSet<string> 的聪明替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com