我有一个字符串数组,例如“blue”,“green”,“red”,我希望对它们进行排序,以便最长的字符串排在最前面,最短的字符串排在最后。
目前,我正在创建另一个数组,该数组的每个字符串的长度都在相同的索引位置,并使用此数组作为键数组进行排序,如下所示,但是我认为可以将其优化为一行吗?
Dim colours() As string = {"blue", "green", "red"}
Dim colourslength() As Integer
For i As Integer = 0 To colours.Length - 1
colourslength(i) = colours(i).Length
Next
Array.Sort(colourslength, colours)
Array.Reverse(colours)
编辑:刚刚意识到我在示例代码中将颜色定义为列表,这是我实际代码中的一个数组。
最佳答案
我认为这是捷径。使用linq。
Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderBy(Function(x) x.Length).ThenBy(Function(x) x).ToArray()
编辑
如果您想要相反的顺序,只需摆脱多余的方法调用即可,以相反的顺序进行sortin
Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderByDescending(Function(x) x.Length).ThenByDescending(Function(x) x).ToArray
干杯。
关于vb.net - 如何按字符串长度对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10014417/