A case-insensitive ordinal string comparison with StringComparison.OrdinalIgnoreCase

Views: 5710
Comments: 0
Like/Unlike: 0
Posted On: 27-May-2021 06:07 

Share:   fb twitter linkedin
Smith
2890 Points
78 Posts


The StringComparison has the OrdinalIgnoreCase property and treats the characters in the strings to compare as if they were converted to uppercase (using the conventions of the invariant culture) and then it performs a simple byte comparison  and it is independent of language. 

This is most useful when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.

Definition

String.Compare(strA, strB, StringComparison.OrdinalIgnoreCase);

is equivalent to (but faster than) this comparison:

String.Compare(strA.ToUpperInvariant(), strB.ToUpperInvariant(), StringComparison.Ordinal);

Example I)

var strA = "AbC";
var strB = "abc";
            
if(String.Compare(strA, strB, StringComparison.OrdinalIgnoreCase)==0)
    Console.WriteLine("strA and strB are in same position");
else
    Console.WriteLine("strA and strB are in same position");

Output

Example II)

var strA = "AbC";
var strB = "abc";

if (String.Compare(strA.ToUpper(), strB.ToUpper(), StringComparison.Ordinal) == 0)
    Console.WriteLine("strA and strB are in same position");
else
    Console.WriteLine("strA and strB are in same position");

Output

0 Comments
 Log In to Chat