I have written the following extension:
<Extension>
Public Sub SortByLengthDescending(ByVal uList As List(Of String))
uList.OrderByDescending(Function(c) c.Length)
End Sub
The list of string looks like this:
[0] = "short text"
[1] = "very very very very long text"
I expect the function to sort the list so that it looks like this:
[0] = "very very very very long text"
[1] = "short text"
But that doesn't happen.
Here is my code:
Dim nTest As New List(Of String)
nTest.Add("short text")
nTest.Add("very very very very long text")
nTest.SortByLengthDescending
What am I missing?
Edit:
I have now found this:
<Extension>
Public Sub SortByLengthDescending(ByVal uList As List(Of String))
Dim comparison As Comparison(Of String) =
Function(x, y)
Dim rslt = x.Length.CompareTo(y.Length)
Return If(rslt = 0, rslt, x.CompareTo(y))
End Function
uList.Sort(comparison)
End Sub
But even this does not work right.
Here are the results:
In this example one can see that [5] is indeed longer than
Thank you!
CodePudding user response:
You need to use ByRef to change the original list:
Imports System.Runtime.CompilerServices
Module ListExtensions
<Extension>
Sub OrderByLengthDescending(ByRef stringList As List(Of String))
stringList = stringList.OrderByDescending(Function(s) s.Length).ToList()
End Sub
End Module
So...
Module Module1
Sub Main()
Dim a As New List(Of String) From {"AB", "ABC", "A"}
a.OrderByLengthDescending()
Console.WriteLine(String.Join(", ", a))
Console.ReadLine()
End Sub
End Module
Outputs:
ABC, AB, A
CodePudding user response:
You need to get the reference to that object. You're taking its value. This link explains it well.