-2

I'm trying to compare string values:

using System;

public class Test
{
    public static void Main()
    {
        int cmpValue = String.Compare("N-1.2.0.10", "N-1.2.0.8", StringComparison.InvariantCultureIgnoreCase);
        if(cmpValue > 0)
            Console.WriteLine("greater");

        cmpValue = String.Compare("N-1.2.0.10", "N-1.2.1.10", StringComparison.InvariantCultureIgnoreCase);
        if(cmpValue < 0)
            Console.WriteLine("lesser");

        cmpValue = String.Compare("N-1.2.0.10", "N-1.2.0.10", StringComparison.InvariantCultureIgnoreCase);
        if(cmpValue == 0)
            Console.WriteLine("equal");
    }
}

This prints:

lesser
equal

For some reason, the greater case doesn't print. Why isn't "N-1.2.0.10" considered greater than "N-1.2.0.8"?

  • 3
    The 1 is less than the 8 when comparing character by character (it is not a numeric comparison). – Jason Down Nov 11 '14 at 18:02
  • You'll need to parse out the numeric values and compare them to get the results you want. – juharr Nov 11 '14 at 18:03
  • 1
    I always love these _optimistic programming_ questions. `Twelve` is greater than `Pi`, but `Three` sorts between them. And `III` doesn't equal `3` or `Three`! Why doesn't .NET do the right thing? – HABO Nov 11 '14 at 18:06
  • Is the `N-` part a constant, or it can also change? – Pierre-Luc Pineault Nov 11 '14 at 18:07

2 Answers2

3

Why would it? String comparisons are performed character by character (with a few possiblt exceptions that do not apply here), and '1' compares as less than '8'.

The type of sorting you're looking for, where "10" compares as greater than "8", is often called a "natural sort", for which .NET Framework doesn't provide any options directly, but which is easy to create yourself (or let the native WinAPI do the work).

Community
  • 1
  • 1
2

That happens because the strings are ordered alphabetically, not numerically:

10
11
12
20
8
etc.
Tea With Cookies
  • 950
  • 6
  • 18