Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options of the StringComparison Enumeration

I'm confused by the options of the StringComparison Enumeration. I just want to compare two strings ignoring case. Can someone explain what the terms current culture, invariant culture and ordinal mean? Is there an option common to most use cases, and if so, under what circumstances would the other options be needed?

For reference, the options of the StringComparison enum is as follows:

  • CurrentCulture
  • CurrentCultureIgnoreCase
  • InvariantCulture
  • InvariantCultureIgnoreCase
  • Ordinal
  • OrdinalIgnoreCase
like image 377
Dan Stevens Avatar asked Feb 23 '12 16:02

Dan Stevens


People also ask

What is the use of StringComparison OrdinalIgnoreCase?

OrdinalIgnoreCase. 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.

What is StringComparison InvariantCulture?

The StringComparison enumeration is used to specify whether a string comparison should use the current culture or the invariant culture, word or ordinal sort rules, and be case-sensitive or case-insensitive. Important.

What is StringComparison CurrentCultureIgnoreCase?

The StringComparer returned by the CurrentCultureIgnoreCase property can be used when strings are linguistically relevant but their case is not. For example, if strings are displayed to the user but case is unimportant, culture-sensitive, case-insensitive string comparison should be used to order the string data. .


2 Answers

If you are comparing two strings for equality then the culture settings don't make much difference (though it affects, for example, Turkish, which has dotted and undotted i's).

If you are sorting a list of strings there's a big difference; different cultures often sort in different orders.

CurrentCulture sorts strings according to, erm, the current culture (i.e. the current locale). So this changes depending on where your software is run.

InvariantCulture is basically US English settings. It's invariant because it's the same wherever your software runs.

Ordinal comparisons are based on the values of the Unicode code points. This is usually the best choice for comparing equality, but not a good choice if you are sorting a list of strings to display to the user.

like image 188
arx Avatar answered Oct 07 '22 17:10

arx


See http://blogs.msdn.com/b/abhinaba/archive/2005/10/28/486173.aspx and http://msdn.microsoft.com/en-us/library/ms973919. Recommendation is to use Ordinal* methods.

like image 43
Shan Plourde Avatar answered Oct 07 '22 18:10

Shan Plourde