您的位置:首页 > 其它

对AarrayList进行排序

2006-04-19 11:42 99 查看
对AarrayList进行排序

要对ArrayList进行排序还不容易吗?用Sort()方法。非常容易解决的。但是事情真的那么简单吗?

如果情况是这样的:

Dim al As New System.Collections.ArrayList
Dim syncal As System.Collections.ArrayList
syncal = System.Collections.ArrayList.Synchronized(al)

syncal.Add("abc")
syncal.Add("def")
syncal.Add("hijklmnop")

要进行排序,就这样调用Sort()方法:

syncal.Sort()

这样作当然是正确的,但是如果需要的是倒序又该怎么办?答案是实现System.Collections.IComparer接口。如下所示:

Public Class DESC
Implements System.Collections.IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
If x > y Then
Return -1
End If
If x < y Then
Return 1
End If
If x = y Then
Return 0
End If
End Function
End Class

然后在调用ArrayList的Sort()方法时把该类的一个实例作为参数传递给Sort()方法。

Console.WriteLine("")

syncal.Sort(New DESC)

For Each obj As Object In syncal
Console.WriteLine(obj.ToString)
Next

这样就按照倒序排列了。

完整的代码如下:

Module Module1

Sub Main()
Dim al As New System.Collections.ArrayList
Dim syncal As System.Collections.ArrayList
syncal = System.Collections.ArrayList.Synchronized(al)

syncal.Add("hijklmnop")
syncal.Add("abc")
syncal.Add("def")

syncal.Sort()

For Each obj As Object In syncal
Console.WriteLine(obj.ToString)
Next

Console.WriteLine("")

syncal.Sort(New DESC)

For Each obj As Object In syncal
Console.WriteLine(obj.ToString)
Next

Console.ReadLine()
End Sub

Public Class DESC
Implements System.Collections.IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
If x > y Then
Return -1
End If
If x < y Then
Return 1
End If
If x = y Then
Return 0
End If
End Function
End Class

End Module
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: