我想在一个窗口中显示几个字符串。在将这些字符串添加到列表中之前,我已经计算了所有这些字符串的列文斯丁距离。
现在,我想从距离最短的字符串开始对列表进行排序。有什么方法可以不使用第二个列表吗?我使用的是VB.NET。
我使用VB.NET,谢谢
你可以传递一个自定义的比较方法给List sort-method。
语法如下,其中 "YourComparer "是一个用你的实现来比较两个字符串的函数,"list "是一个字符串的列表。
list.Sort(Function(s1, s2) YourComparer(s1, s2))
"YourComparer "应该返回一个给定的两个字符串的整数值,指示第一个字符串是否应该在第二个字符串之前、之后或具有相同的位置。
下面是一个实现的例子。
Private Function YourComparer(ByVal s1 As String, ByVal s2 As String) As Integer
' **** compare using your own implementation ****
' return less than zero if s1 should preceed s2
' return zero if s1 has same position in sort order
' return greater than zero if s1 should follow s2
' EXAMPLE using the length of strings to determine sort order
' Replace section with your own implementation
If (s1.Length = s2.Length) Then Return 0 ' same position
If (s1.Length > s2.Length) Then Return -1 ' should come before
Return 1 ' should come after
End Function