I've got a whitelist of URLs I'm using, inside a HashSet<string>
. I'm trying to find if the url
starts with any of the items in the white list (it has to be that way round).
Edit: The previous example was a bit misleading and had a typo - I already have a base url like yahoo.com, the whitelist is just the path.
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;
}
}
Is there a more elegant way of doing this lookup with LINQ (to objects)? The list isn't huge so performance isn't an issue.
bool validUrl = whiteList.Any(item => linkUrl.StartsWith(item));
By the way, in general, hash tables are not good data structures for these kind of problems (where you don't have the key and are matching the key based on a function) as you'll have to enumerate the whole table all the time. You can use a simple List<string>
to hold the items instead and you'll get better performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With