The Dictionary class does not have inbuilt sort functionality and I was looking for a simple way to sort on the Values within the collection.
After searching google, it became clear that there are several ways to achieve this, from implementing Lists, using LookUps and even making use of LINQ. I just wanted something quick and dirty that gets the job done. Wasn't concerned with overheads or speed of execution. There is even an Article here on codeproject
A Dictionary Collection Sorting By Value[
^] which as you can see is way in excess of my simple function. However, if you are looking for a professional way to do it, then it maybe better to implement something like that.
My dictionary consisted of a
String Key, Integer Value pair where the String Key represent an equipment tagname, and the Integer Value was the number of records that were present in the alarm / event logs (the returned database records), e.g.
"TagDEF", 364
"TagXYZ", 2102
"TagABC", 56
"TagMNO", 100
"TagJKL", 10
So I knocked up this simple function, where the dictionary is passed in, and a new value sorted dictionary is returned. Now, don't get me wrong, my version is maybe just a dirty hack, but it works and gets the job done. It is simple to follow [good for non-pro's like me], although it maybe isn't the worlds fastest function, it gets the job done.
Going, by the number of questions I have seen on the net, I thought I would share it.
Private Function DictValueSortDesc(ByVal SourceDictionary As Dictionary(Of String, Integer)) As Dictionary(Of String, Integer)
Dim inDict As Dictionary(Of String, Integer) = SourceDictionary
Dim outDict As New Dictionary(Of String, Integer)
Dim currentMaxKey As String = String.Empty
Dim currentMaxValue As Integer = 0
Do While inDict.Keys.Count > 0
For Each currentKVP As KeyValuePair(Of String, Integer) In inDict
If currentKVP.Value >= currentMaxValue Then
currentMaxKey = currentKVP.Key
currentMaxValue = currentKVP.Value
End If
Next
outDict.Add(currentMaxKey, currentMaxValue)
inDict.Remove(currentMaxKey)
currentMaxValue = 0
Loop
Return outDict
End Function
So for the Dictionary example above, the output dictionary would look like;
"TagXYZ", 2102
"TagDEF", 364
"TagMNO", 100
"TagABC", 56
"TagJKL", 10