对AarrayList进行排序

 

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


然后在调用ArrayListSort()方法时把该类的一个实例作为参数传递给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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值