2

我有一个字符串数组,例如“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)

编辑:刚刚意识到我在示例代码中将颜色定义为一个列表,它是我实际代码中的一个数组。

4

4 回答 4

4

另一个 Linq 解决方案(警告,从 C# 转换而来)

Dim Sorted = From p In colours Order By p.Length Descending Select p
于 2012-04-04T15:45:45.523 回答
3

在我看来,这是短裤的方式。使用 linq。

Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderBy(Function(x) x.Length).ThenBy(Function(x) x).ToArray()

编辑

如果你想要一个相反的顺序,只需摆脱额外的方法调用,并以相反的顺序进行排序

Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderByDescending(Function(x) x.Length).ThenByDescending(Function(x) x).ToArray

干杯。

于 2012-04-04T15:41:35.977 回答
2
Dim colours = {"blue", "green", "red"}
Dim coloursSortedByLength = colours.OrderByDescending(Function(c) c.Length)

输出顺序为:绿、蓝、红。

于 2012-04-04T15:43:00.833 回答
1

最好的简单方法是将每个字符串与列表中的所有其他字符串进行比较:

在 Java 中:

for(int i=0; i<list.length-1; i++){
    for(int j=i+1; j<list.length; j++){
        if(list[i].length() < list[j].length()){
            tmp = list[i];
            list[i] = list[j];
            list[j] = tmp;
        }
    }
}
于 2012-04-04T15:49:04.570 回答