数组排序2
Posted VB.Net
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组排序2相关的知识,希望对你有一定的参考价值。
版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
对于类的排序,首先要实现 IComparable接口。它定义一种特定于类型的通用比较方法,值类型或类通过实现此方法对其实例进行排序。
以下是一个学生类,仅包含学生学号id(Integer)和姓名name(String)。确保该类实现了IComparable接口,并在类里实现了CompareTo方法:
Public Class student
Implements IComparable(Of student)
Public Function CompareTo(other As student) As Integer Implements IComparable(Of student).CompareTo
……
End Function
具体代码如下
Public Class student
Implements IComparable(Of student)
Public Property id As Integer
Public Property Name As String
Sub New(ByVal id As Integer, ByVal Name As String)
Me.id = id
Me.Name = Name
End Sub
Public Function CompareTo(other As student) As Integer Implements IComparable(Of student).CompareTo
Return id.CompareTo(other.id)
End Function
Public Overrides Function ToString() As String
Return id & ":" & Name
End Function
End Class
代码里面默认使用了Integer的CompareTo 方法。
由于涉及后面的输出,这里还重写了ToString方法,按照“学号:姓名”的方式输出。
Sub Main中使用Student类的代码如下:
Dim teststudent() As student = New student()
New student(12, "Bolger"),
New student(13, "Quin"),
New student(11, "Anie"),
New student(10, "Besterman"),
New student(14, "Orvis")
Console.WriteLine("按照学号排序:")
Dim copystudent1() As student
copystudent1 = teststudent.Clone
Array.Sort(copystudent1)
For i As Integer = 0 To copystudent1.Length - 1
Console.WriteLine(copystudent1(i).ToString & " ")
Next
Console.WriteLine()
Console.WriteLine("按照学号倒序:")
Dim copystudent2() As student
copystudent2 = teststudent.Clone
Array.Sort(copystudent2)
Array.Reverse(copystudent2)
For i As Integer = 0 To copystudent2.Length - 1
Console.WriteLine(copystudent2(i).ToString & " ")
Next
Console.WriteLine()
Console.WriteLine("原数组:")
Dim copystudent3() As student
copystudent3 = teststudent.Clone
Array.Sort(copystudent3, AddressOf Comparison)
For i As Integer = 0 To copystudent3.Length - 1
Console.WriteLine(copystudent3(i).ToString & " ")
Next
Console.WriteLine()
Console.ReadKey()
运行如下图所示:
在以上代码中实现了按照id排序,如果以姓名排序呢?
不增加类中的代码,在模块中添加如下代码,使用姓名作比较:
Private Function Comparison(x As student, y As student) As Integer
Return (x.Name).CompareTo(y.Name)
End Function
Sub Main中增加代码:
Console.WriteLine("按照姓名排序:")
Dim copystudent3() As student
copystudent3 = teststudent.Clone
Array.Sort(copystudent3, AddressOf Comparison)
For i As Integer = 0 To copystudent3.Length - 1
Console.WriteLine(copystudent3(i).ToString & " ")
Next
Console.WriteLine()
Console.ReadKey()
Exit Sub
运行结果如下图:
这里使用的是Array的Public Shared Sub Sort(Of T) ( array As T(), comparison As Comparison(Of T) )方法,使用到了Comparison(Of T) 委托,使用如下的声明:
Public Delegate Function Comparison(Of In T) ( _
x As T, _
y As T _
) As Integer
简化的使用方法直接在Sort()方法中使用 Addressof 方法名。
该委托方法返回值如果小于 0,那么x排在y前面。上面的代码简单使用了String的CompareTo方法。
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录
以上是关于数组排序2的主要内容,如果未能解决你的问题,请参考以下文章