.NET: How to determine if a string comes before another string based on the dictionary order
Usually string comparisons are needed just to determine the equality (or inequality) of 2 strings. However, there are times when determining inequality isn't the end in itself. Sometimes a developer also needs to know if a particular string should "come before" another string -- alphabetically , based on the common dictionary order.
The regular relational operators ( <, >, =<. >=) do not work on string variables and/or literals. So using:
if (string1 < string2)
// code here
is out of the question because the compiler will not even allow it. So what's the alternative? As it turns out, the same function that I mentioned for performing case-insensitive string operations (string.Compare), is also capable of determining if the first string parameter alphabetically comes before the second string parameter. The function returns zero (== 0) if the strings are equal, a negative value (< 0) if the first string is "less than" (alphabetically comes before) the second string, and a positive value (> 0) if the first string is "greater than" (alphabetically comes after) the second string. Given this, the following code will return a negative value:
whereas this will return a positive value:
Now, if the strings are not of equal length, the longer string is always considered "greater" than the shorter string. So the following code will return a negative value:
And, of course, you can perform case-insensitive comparisons, e.g.
string.Compare("b22", "B21", false);
As always, please refer to the MSDN documentation for additional information. Link