Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A clever alternative in LINQ for iterating over HashSet<string>

Tags:

c#

linq

hashset

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.

like image 782
Chris S Avatar asked Dec 13 '22 00:12

Chris S


1 Answers

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.

like image 59
mmx Avatar answered Feb 11 '23 02:02

mmx