如何使用列文斯丁距离作为标准对一个列表进行排序?

问题描述 投票:0回答:1

我想在一个窗口中显示几个字符串。在将这些字符串添加到列表中之前,我已经计算了所有这些字符串的列文斯丁距离。

现在,我想从距离最短的字符串开始对列表进行排序。有什么方法可以不使用第二个列表吗?我使用的是VB.NET。

我使用VB.NET,谢谢

vb.net sorting levenshtein-distance
1个回答
0
投票

你可以传递一个自定义的比较方法给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
© www.soinside.com 2019 - 2024. All rights reserved.