2008/08/23(Sat) 18:00:57 編集(投稿者)
Imports System
Imports System.Collections.Generic
Public Structure データ
Public key1 As String
Public key2 As String
Public key3 As String
End Structure
Public Class MultiKeyComp(Of T)
Implements IComparer(Of T)
Dim comps() As Comparison(Of T)
Public Function Compare(ByVal x As T, ByVal y As T) As Integer _
Implements IComparer(Of T).Compare
For Each c As Comparison(Of T) In comps
Dim result As Integer = c(x, y)
If result <> 0 Then Return result
Next
Return 0
End Function
Public Sub New(ByVal ParamArray c() As Comparison(Of T))
comps = c
End Sub
End Class
Public Class Program
Shared Function lt1(ByVal x As データ, ByVal y As データ) As Integer
Return x.key1.CompareTo(y.key1)
End Function
Shared Function gt1(ByVal x As データ, ByVal y As データ) As Integer
Return y.key1.CompareTo(x.key1)
End Function
Shared Function lt2(ByVal x As データ, ByVal y As データ) As Integer
Return x.key2.CompareTo(y.key2)
End Function
Shared Function gt2(ByVal x As データ, ByVal y As データ) As Integer
Return y.key2.CompareTo(x.key2)
End Function
Shared Function lt3(ByVal x As データ, ByVal y As データ) As Integer
Return x.key3.CompareTo(y.key3)
End Function
Shared Function gt3(ByVal x As データ, ByVal y As データ) As Integer
Return y.key3.CompareTo(x.key3)
End Function
Shared Function non(ByVal x As データ, ByVal y As データ) As Integer
Return 0
End Function
Public Shared Sub Main()
Dim N As Integer = 10
Dim data(N - 1) As データ
Dim r As New Random()
For i As Integer = 0 To N - 1
Dim datum As New データ()
With datum
.key1 = r.Next(10).ToString()
.key2 = r.Next(10).ToString()
.key3 = r.Next(10).ToString()
End With
data(i) = datum
Next
Console.WriteLine("ソート前")
For Each item As データ In data
Console.WriteLine("{0} {1} {2}", item.key1, item.key2, item.key3)
Next
Console.WriteLine()
' 昇順,ソートせず,降順 でソートする
Dim c As New _
MultiKeyComp(Of データ)(AddressOf lt1, _
AddressOf non, _
AddressOf gt3)
Array.Sort(data, c)
Console.WriteLine("ソート後")
For Each item As データ In data
Console.WriteLine("{0} {1} {2}", item.key1, item.key2, item.key3)
Next
End Sub
End Class