为了能够按值对字典进行排序我正在使用此代码:
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)
当我使用.ToDictionary方法将List对象转换回Directory对象时,我在“pair.Key”上收到错误说:
类型'String'的值无法转换为'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String,Integer))
我应该如何使用.ToDictionary从我的对象列表中获取Dictionary对象?
如果我使用.ToDictionary方法将行更改为:
idCurrentJobs = jobsSortedByCount.ToDictionary(Of KeyValuePair(Of String, Int32))(Function(pair As KeyValuePair(Of String, Int32)) pair)
由于“Strict On”,我收到此错误:
Option Strict On禁止隐含 来自的转换 “System.Collections.Generic.Dictionary(中 System.Collections.Generic.KeyValuePair(中 String,Integer), System.Collections.Generic.KeyValuePair(中 String,Integer))'到 “System.Collections.Generic.IDictionary(中 字符串,整数)'
我该如何解决这个问题?
答案 0 :(得分:7)
即使使用Option Strict On
,这也可以。
Dim list As List(Of KeyValuePair(Of String, Int32))
Dim dict As IDictionary(Of String, Int32) =
list.ToDictionary(Function(p) p.Key, Function(p) p.Value)
问题就在于您的代码:
ToDictionary(Of List(Of KeyValuePair(Of String, Int32)))
答案 1 :(得分:2)
尝试:
idCurrentJobs = jobsSortedByCount.ToDictionary(Of String, Int32)(Function(p) p.Key, Function(p) p.Value)