Sorting a list of strings basing on numbers inside the elements

Assume we want to order by the prices (i.e. 1.89, 1.79, 2.14 becomes 1.79, 1.89, 2.14).
We can use a C# snippet that orders the list by a custom value, and we use regex to parse the number from the string.

We then cast it to double (with invariant culture so that both , and . are accepted as decimal separators) and it will automatically compare the numbers.

  value = ["NV 1024   1.89", "NV 1033   1.79", "NV 1233   2.14"]
  => VAR @list

var sorted = list.OrderBy(s => 
    System.Text.RegularExpressions.Regex.Match(s, @"\d+\.\d+").Value,

Now the sorted variable will have a sorted list of strings.

1 Like