How to compare strings differentiating case from case?

Asked

Viewed 1,011 times

4

I have following code:

Usuarios user = DataModel.Usuarios.Where(x => x.Login.Equals(login,StringComparison.OrdinalIgnoreCase) && x.Senha.Equals(senha,StringComparison.Ordinal)).FirstOrDefault();

I would like the following result:

"login" == "Login" |true|
"senha" == "Senha" |false|

3 answers

7

You can use the property Invariantcultureignorecase class StringComparer, see:

string str1 = "Stack";
string str2 = "stack";

Console.WriteLine(str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine(str1.Equals(str2));

Exit:

True
False

See working on .Net Fiddle.

  • But AP asked how to differentiate between upper and lower case. The StringComparison.InvariantCultureIgnoreCase does not do otherwise?

  • @vnbrs by what I understand is to ignore the case-sensitive, the above function does this, and the below does not ignore the case-sensitive.

7

You are comparing the password as follows:

x.Senha.Equals(senha, StringComparison.Ordinal)

According to the documentation the StringComparison.Ordinal makes the case-sensitive comparison, ie considering uppercase and lowercase.

When you’re comparing the user, you’re doing so:

x.Login.Equals(login, StringComparison.OrdinalIgnoreCase)

I don’t know the necessity of using the OrdinalIgnoreCase in your case. I always use the StringComparison.InvariantCultureIgnoreCase to that end, in this way:

x.Login.Equals(login, StringComparison.InvariantCultureIgnoreCase)

If you can, it’s worth reading "Difference between Invariantculture and Oridinal string comparison".

The code you posted already does what you want. That evalua:

"login" == "Login" > true (é case-insensitive)
"senha" == "Senha" > false (é case-sensitive)

5


When passing the parameter StringComparison.OrdinalIgnoreCase you are advising not to differentiate between upper case and lower case, so:

login == Login // Será verdadeiro se o parâmetro for informado

But as you can see, although the word is the same, what differentiates one from the other is the case-sensitive, take this example:

string a = "[email protected]";
string b = "[email protected]";
    
// Ira retornar Falso, porque não foi informado
// para ignorar case-sensitive
if (a.Equals(b)) {
    Console.WriteLine("Verdadeiro");
} else {
    Console.WriteLine("Falso");
}
    
// OrdinalIgnoreCase
// Ira retorna Verdadeiro, porque foi informado
// para ignorar case-sensitive
if (a.Equals(b, StringComparison.OrdinalIgnoreCase)) {
    Console.WriteLine("Verdadeiro");
} else {
    Console.WriteLine("Falso");
}

See working on dotnetfiddle

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.