简体   繁体   中英

VB.Net Order a Dictionary(Of String, Integer) by value of the Integer

I have a dictionary of String, Integer so the key is the string and the value is the integer and i want to order the keys ascending by the value of the integer. How could I achieve this?

You could use LINQ to sort the Dictionary by value:

Dim dictionary = New Dictionary(Of String, Integer)() 
dictionary.Add("A", 2)
dictionary.Add("B", 4)
dictionary.Add("C", 5)
dictionary.Add("D", 3)
dictionary.Add("E", 1)

Dim sorted = From pair In dictionary
             Order By pair.Value
Dim sortedDictionary = sorted.ToDictionary(Function(p) p.Key, Function(p) p.Value)

Actually it does not modify the original Dictionary but creates a new Dictionary with the new order.

But : Apart from the feasability, a Dictionary is not an IList (as an Array or List<T> ). It's purpose is to lookup a key very efficiently but not to loop all entries.

They are unordered, meaning that although you can retrieve the elements in some order with a foreach loop, that order has no special meaning, and it might change for no apparent reason.

First of all, a dictionary does not have an intrinsic order. It is for look-ups. However, you can turn the keys into their own ordered list.

Dim keyList as List(Of String) = (From tPair As KeyValuePair(Of String, Integer) _
                                  In myDictionary Order By tPair.Value Ascending _
                                  Select tPair.Key).ToList

I had to do something similar to this with custom objects. I think this should be close (but may not be exactly) what you're looking for:

Dim sortedL As List(Of KeyValuePair(Of String, Integer)) = yourDictionary.ToList
sortedL.Sort(Function(firstPair As KeyValuePair(Of String, Integer), nextPair As KeyValuePair(Of String, Integer)) CInt(firstPair.Value).CompareTo(CInt(nextPair.Value)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM