0

and DN125I have a list with the following values:

   DN32
   DN100
   DN50
   DN80
   DN125
   DN65

I want to sort this list the following way:

DN125       
DN100
DN80     
DN65   
DN50   
DN32

I tried using:

list.sort()
list.reverse()

but this resulted in DN100 and DN125 ending up at the end of the list. so how can I sort this the way I want to?

Fyer-Zero
  • 123
  • 2
  • 11
  • 1
    You'll need a custom comparison that understands the ordering you require. See the [`Array.Sort`](https://learn.microsoft.com/en-gb/dotnet/api/system.array.sort?view=netframework-4.7#System_Array_Sort_System_Array_System_Array_System_Collections_IComparer_) documentation.(the right overload will depend on the details of your array which you don't show). – Richard Nov 15 '17 at 09:46

1 Answers1

2

Since the list contains strings, List.Sort will perform an alphanumeric sorting. You want to sort the first part alphabetically and the numerical part numerically, like windows explorer.

If this format is fix(first 2 letters are letters, rest is an integer) you could use this LINQ approach:

list = list.
    Select(Function(s) New With {.String = s, .Letters = s.Remove(2), .Number = Int32.Parse(s.Substring(2))}).
    OrderBy(Function(x) x.Letters).
    ThenBy(Function(x) x.Number).
    Select(Function(x) x.String).
    ToList()
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939