Carl Onager
Carl Onager

Reputation: 4122

Why is .Contains not functioning as expected?

I'm translating some code from C# to VB.NET and getting an odd problem. I have a class that takes an array of URls as strings and checks them against a given request to build a route. Here's the C# code:

string requestedurl = httpContext.Request.AppRelativeCurrentExecutionfilePath;
if (urls.Contains(requestedurl, StringCompraer.OrdinalIgnoreCase)) {
    //Do stuff
    }

I've translated it into this:

Dim requestedurl As String = httpContext.Request.AppRelativeCurrentExecutionFilePath
If urls.Contains(requestedurl, StringComparer.OrdinalIgnoreCase) = True Then
    'Do stuff
End If

The urls array contains a couple of strings beginning with '~/' and the requestedurl is '~/' so that should be a match. However the code above never executes the 'do stuff' section.

As an alternative I tried this which works fine:

For Each url As String In urls
    If url.ToLower.Contains(requestedurl.ToLower) = True Then
        'Do stuff
        Exit For
    End If
Next

Why is the Contains extension in the first example functioning differently than the String.Contains method in the second and is there a better way to translate this?

Upvotes: 0

Views: 157

Answers (1)

SBI
SBI

Reputation: 2322

"The urls array contains a couple of strings beginning with '~/' and the requestedurl is '~/' so that should be a match." -> No, it shouldn't. Contains checks for absolute matches, and not if any of the strings in the array contain that string. The Contains extension method on arrays only checks whole strings, as opposed to the Contains method on string, which checks to see if a string contains the substring you're looking for. That's exactly why your second example works.

This will output nothing:

string[] urls = { "bla", "~/something/some_folder", "ab", "cd", "~/some_file" };
string requestedUrl = "~/";
if (urls.Contains(requestedUrl, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Check");
}

whereas this:

string[] urls = { "bla", "~/something/some_folder", "~/", "~/", "~/some_file" };
string requestedUrl = "~/";
if (urls.Contains(requestedUrl, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Check");
}

Will output check. If that's your 1:1 code conversion, the original doesn't work.

You can leverage Linq to your needs if you want to avoid the loop by using something like:

if (urls.Any(url => url.Contains(requestedUrl)))
{
    Console.WriteLine("Check");
}

You'll have to do the conversion to VB.Net by yourself, as I'm not familiar with the language.

Upvotes: 3

Related Questions