Sort a 2 level dictionary

swap123

Member
Joined
Aug 11, 2009
Messages
6
Programming Experience
1-3
Hi,

I have a dictionary in VB.Net

Dim fileDetailsDictionary As New Dictionary(Of String, Dictionary(Of String, String))

In the Value of fileDetailsDictionary , I have 3 keys

key1, key2, key3

I want to sort the whole dictionary by Key3

Anybody has any thoughts on this?


Thanks!!!
 
You really want to sort this by the last value in the line?
This is going to be kinda nasty...ahhh, I mean nested...*ahem*

No wait...you want it to sort by which value?
VB.NET:
Dictionary (fileDetailsDictionary)
   --> KeyValuePair
      * Key 1
      # Value 1 : Dictionary
         --> KeyValuePair
            * Key 1.1
            # Value 1.1

You want to sort this by Value 1.1?

Bobby
 
To do that you have to get the main key list and sort that in relation to the value objects. Since dictionaries are indexed by key and not placement in list you also have to the get the sub keys to a list if you want to compare the third item (placement) of each sub dictionary.
VB.NET:
Private d As New Dictionary(Of String, Dictionary(Of String, String))

Private Function Compare(ByVal x As String, ByVal y As String) As Integer
    Return d(x)(d(x).Keys(2)).CompareTo(d(y)(d(y).Keys(2)))
End Function
VB.NET:
d("3") = New Dictionary(Of String, String)
d("3").Add("A", "3.1")
d("3").Add("B", "3.2")
d("3").Add("C", "3.3")
d("2") = New Dictionary(Of String, String)
d("2").Add("A", "2.1")
d("2").Add("B", "2.2")
d("2").Add("C", "2.3")
d("1") = New Dictionary(Of String, String)
d("1").Add("A", "1.1")
d("1").Add("B", "1.2")
d("1").Add("C", "1.3")
VB.NET:
Dim keys = d.Keys.ToList
keys.Sort(AddressOf Compare)
For Each key In keys
    Console.WriteLine(key)
Next

'the out is:
' 1 (based on string "1.3")
' 2 (based on string "2.3")
' 3 (based on string "3.3")
I think this sample code should work with VB 2005, at least I remembered to not use lamba function this time ;)
 
Back
Top