How to compare strings in case sensitive?

3

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 to get the following result:

"login" == "Login" |true|
"senha" == "Senha" |false|
    
asked by anonymous 13.10.2017 / 05:54

3 answers

4

By passing the StringComparison.OrdinalIgnoreCase parameter you are advising not to be case-sensitive, 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 case-sensitive , see 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 at dotnetfiddle

Reference

13.10.2017 / 06:20
5

You can use the InvariantCultureIgnoreCase property. of class StringComparer , see:

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

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

Output:

  

True
  False

See working at .Net Fiddle .

    
13.10.2017 / 20:41
5

You are comparing the password as follows:

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

According to the documentation, the StringComparison.Ordinal makes the comparison case-sensitive, that is, case-sensitive.

When you are comparing the user, you are doing so:

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

I do not know the need to use OrdinalIgnoreCase in your case. I always use StringComparison.InvariantCultureIgnoreCase for this purpose, like this:

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

If you can, read " Difference between InvariantCulture and Oridinal string comparison

The code you posted already does what you want. This evaluates :

"login" == "Login" > true (é case-insensitive)
"senha" == "Senha" > false (é case-sensitive)
    
13.10.2017 / 20:59