To be able to sort a dictionary by value I’m using this code:
Dim idCurrentJobs As IDictionary(Of String, Int32) = New Dictionary(Of String, Int32)
'The string in the dictionary represents a jobname and the integer is a counter for how many jobs im currently are running in the application'
idCurrentJobs.Add("JobName1", 2)
idCurrentJobs.Add("JobName2", 1)
idCurrentJobs.Add("JobName3", 2)
idCurrentJobs.Add("JobName4", 5)
idCurrentJobs.Add("JobName5", 3)
idCurrentJobs.Add("JobName6", 4)
Dim jobsSortedByCount As List(Of KeyValuePair(Of String, Int32)) = New List(Of KeyValuePair(Of String, Int32))(idCurrentJobs)
jobsSortedByCount.Sort(Function(firstPair As KeyValuePair(Of String, Int32), nextPair As KeyValuePair(Of String, Int32)) firstPair.Value.CompareTo(nextPair.Value))
idCurrentJobs = jobsSortedByCount.ToDictionary(Of List(Of KeyValuePair(Of String, Int32)))(Function(pair As KeyValuePair(Of String, Int32)) pair.Key)
The when I’m using the .ToDictionary method to convert the List object back to a Directory object I’m getting a error on the “pair.Key” saying:
Value of type ‘String’ cannot be converted to ‘System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, Integer))
How should I use the .ToDictionary to get a Dictionary object from my list of objects?
If i change the row with the .ToDictionary method to this:
idCurrentJobs = jobsSortedByCount.ToDictionary(Of KeyValuePair(Of String, Int32))(Function(pair As KeyValuePair(Of String, Int32)) pair)
I get this error because of “Strict On”:
Option Strict On disallows implicit
conversions from
‘System.Collections.Generic.Dictionary(Of
System.Collections.Generic.KeyValuePair(Of
String, Integer),
System.Collections.Generic.KeyValuePair(Of
String, Integer))’ to
‘System.Collections.Generic.IDictionary(Of
String, Integer)’
How can i solve this?
This will work, even with
Option Strict On.The problem is right here from your code: