Simple question about sorting methods in VB.Net

Hi all,

Simple VB.Newbie question.

I am stuck on the utilisation of the sorting method in VisualStudio:

Can somebody explain me why

 

Array.sort(myValues.ToArray, theStuffIWantToSort)

 

instead of updating "theStuffIWantToSort" (and "MyValues") so if I use it further, it will be sorted, don't modify anything (when I output "theStuffIWantToSort", the order never changes)?

 

Thank you for your help,

TS.

  • up

    David Rutten

    Hi Thibault,

     

    when you call ToArray() on a List(Of T) you get a new array instance, filled up with the same elements as the list. Any modifications to this array will pass unnoticed from the point of view of the list.

     

    You need to create two arrays, sort them using the key/value approach you pasted above, then move the arrays back into the lists. The easiest way to achieve this would be:

     

    'Create lists.

    Dim myKeys As New List(Of Double)

    Dim myValues As New List(Of Whatever)

    'Fill up myKeys and myValues with whatever data you want

     

    'Perform sorting step.

    Dim arrKeys As Double() = myKeys.ToArray()

    Dim arrValues As Whatever() = myValues.ToArray()

    Array.Sort(myKeys, myValues)

     

    'Put arrays back into lists.

    myKeys.Clear()

    myValues.Clear()

    myKeys.AddRange(arrKeys)

    myValues.AddRange(arrValues)

     

     

    List(Of T) also supports a fair amount of sorting logic, it may be possible to achieve your goals without round-tripping to arrays.

     

    --

    David Rutten

    david@mcneel.com

    Poprad, Slovakia

    • up

      Thibault Schwartz

      Thanks a lot for your quick and very precise answer David,

      I will try that this evening.

      Thanks again, 

      TS.