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?

1
  • 1
    You'll need a custom comparison that understands the ordering you require. See the Array.Sort documentation.(the right overload will depend on the details of your array which you don't show). Commented Nov 15, 2017 at 9:46

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Works like a charm! Thanks! Added a list.Reverse() to swap the order and now it is perfect.
@Fyer-Zero dont use reverse but OrderByDescending
That also works, saves me a line of code :)
@Flyer: it doesnt only save you a line. You can also use ThenByDescending if you want to sort the ltter part different to the number part. It's also more efficient because a list.Sort at the end would again sort the whole list, so the same procedure again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.