2012年5月17日木曜日

VBでHashTableが入ったArrayListをSortする

結構探し回ったんだけど全然わかんなかったが最終的にここを参考に作業を進めた。
以下のような頭の悪いサンプルデータをComparerを使ってソートしたい。
Dim itemList As new ArrayList 
Dim item1 As new HashTable
item1.add("key1", 10)
item1.add("key2", 20)
item1.add("key3", 30)
Dim item2 As new HashTable
item2.add("key1", 20)
item2.add("key2", 20)
item2.add("key3", 20)
Dim item3 As new HashTable
item3.add("key1", 30)
item3.add("key2", 20)
item3.add("key3", 90)
Dim item4 As new HashTable
item4.add("key1", 110)
item4.add("key2", 220)
item4.add("key3", 330) 
itemList.add(item1)
itemList.add(item2)
itemList.add(item3)
itemList.add(item4)

Comparerでソートするのはjavaで(compareterか?)使ったことがあったので知っていたが、VBではどうやって型を指定するのかさっぱりで結構つまった。
    Public Class ItemSort
        Implements System.Collections.Generic.IComparer(Of Hashtable)
        Public Function Compare(ByVal candidate1 As System.Collections.Hashtable, ByVal candidate2 As System.Collections.Hashtable) As Integer Implements System.Collections.Generic.IComparer(Of System.Collections.Hashtable).Compare

            Dim resultKey1 As Integer = candidate1("key1") - candidate2("key1") '昇順
            'key1が同じときはkey2の降順で返す
            If resultKey1 = 0 Then
                Dim resultKey2 As Integer = candidate2("key2") - candidate1("key2")  '降順
                If resultKey2 = 0 Then
                    'key2が同じときはkey3の昇順で返す
                    Return Comparer.Default.Compare(candidate1("key3"), candidate2("key3")) '昇順
                Else
                    Return resultKey2
                End If
            End If
            'それ以外のときは区分の昇順で返す
            Return resultKey1
        End Function
    End Class
上記のように書いて以下のようにして以下のように呼び出す。
itemList.Sort(New ItemSort)
これでHashTableのfieldでソートかけれる。
超便利^^

0 件のコメント:

コメントを投稿