User4
User4

Reputation: 1350

Can not get .Contains to work in c#

I've been searching and trying various things for hours and can not get this simple contains function to work.

if (department.ToLower().Contains(item2.Title.ToLower()))

Here is an image of the two strings. I've copied them to notepad to compare them and they're identical. enter image description here

Thanks for any advice you might have.

Here are the two string in text, copied straigth from visual studio debugger:

String 1 : "Shared Services - Technology and Information Services"
String 2 : "Shared Services - Technology and Information Services"

Edit - Added strings in text

Upvotes: 1

Views: 1941

Answers (3)

Post Impatica
Post Impatica

Reputation: 16413

This is not 100% related to the OP's question but it is related and I wanted to help anyone else that may stumble on this like I did in .Net 8.

This code will not work:

var first = request.Headers.TryGetValue("Content-Type", out var contentType);
var second = contentType.Contains("application/xml") || contentType.Contains("text/xml");
return first && second;

the variable second will always be false even though when I inspect the contentType of the request header it clearly shows "application/xml; charset=utf-8" as the value.

Apparently the .Contains method doesn't work the way I expected on a StringValues object which is what the variable contentType is. I just assumed the contentType variable was a string and I spent hours troubleshooting this!

So in short, convert the StringValues object to a string and then it works fine.

Upvotes: -1

User4
User4

Reputation: 1350

Looks like it's just been a visual studio compiler bug. I've just ended up restarting my PC and it seems to be working fine now.

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

The code should work (based on the csharp interactive shell):

$ csharp
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> var dep="Shared Services - Technology and Information Services";
csharp> var oth="Shared Services - Technology and Information Services"; 
csharp> dep.ToLower().Contains(oth.ToLower())               
true

Are you sure the code with the if statement is executed, perhaps you should copy the values here, because there might be a small difference (a space for instance).

Based on the image it seems there are two spaces after the dash (-) in the department string. But this can be a trick of the font. But in general it's very bad to use an image instead of providing raw text data (that can be copied and processed).

Upvotes: 3

Related Questions