Search code examples
c#sortingienumerable

C# Order Items By Leading Zeros


I need to order items in an IEnumerable based on a string property that contains leading 0s. The items need to be ordered by 000. then 00. and then it goes to 0.

A simplified example:

Unordered - ["0.4","0.1", "0.3", "00.5", "000.1", "1.2", "00.2", "2.1"]

Ordered -   ["000.1", "00.2", "00.5", "0.1", "0.3", "0.4", "1.2", "2.1"]

The current implementation is:

items.OrderBy(x => x.age);

which orders the items as ["0.1", "0.3", "0.4", "00.2", "00.5", "000.1", "1.2", "2.1"]

Since these are strings, I thought I might try to convert them to decimals, but I'm still not getting the order I need.

items.OrderBy(x => decimal.Parse(x.age))

[ 0.1, 000.1, 00.2, 0.3, 0.4, 00.5,  1.2, 2.1]

Any advice on how to get the order I need would be greatly appreciated!


Solution

  • I suggest comparing strings; the difficulty is that '.' < '0'; to have a required order we can try changing '.' into some other delimiter that's lexicographically bigger then any digit. Let it be a letter, say 'x':

     var result = items.OrderBy(item => item.Replace('.', 'x'));
    

    Demo:

      string[] items = new string[] {
        "0.4","0.1", "0.3", "00.5", "000.1", "1.2", "00.2", "2.1"
      };
    
      var result = items
        .OrderBy(item => item.Replace('.', 'x'));
    
      Console.Write(string.Join(", ", result));
    

    Outcome:

      000.1, 00.2, 00.5, 0.1, 0.3, 0.4, 1.2, 2.1