LINQ中的一个聪明的替代方法,用于迭代HashSet <string>

Chr*_*s S 4 c# linq hashset

我有一个我正在使用的URL列入白名单HashSet<string>.我试图找到是否以url白名单中的任何项目开始(它必须是那样).

编辑:前面的例子有点误导,并有一个错字 - 我已经有一个像yahoo.com的基本网址,白名单只是路径.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Meh*_*ari 12

bool validUrl = whiteList.Any(item => linkUrl.StartsWith(item));
Run Code Online (Sandbox Code Playgroud)

顺便说一下,一般来说,哈希表不是这类问题的好数据结构(你没有密钥并且基于函数匹配密钥),因为你必须枚举整个表所有的时间.您可以使用简单的方式List<string>来保存项目,从而获得更好的性能.