C# Order Items By Leading Zeros

Viewed 117

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!

3 Answers

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

Welcome to Stack Overflow, I think this snippet may help you:

items.OrderBy(x => x.age.Split('.')[0].Length).ThenBy(x => decimal.Parse(x.age));

With this snippet, we split the value on the decimal dot, and then OrderBy the count of 0's on the first part, and if we have two values with the same count of leading zeros, we compare them as ordinary decimals.

Try the following:

items.OrderBy(x => x.Split(".")[0]).ThenBy(x => x.Split(".")[1]);
Related