使用.ToDictionary将List(Of KeyValuePair(Of String,Int32)转换为Dictionary(Of String,Int32))

Jon*_*nas 2 .net vb.net sorting list todictionary

为了能够按值对字典进行排序,我正在使用此代码:

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)
Run Code Online (Sandbox Code Playgroud)

当我使用.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)
Run Code Online (Sandbox Code Playgroud)

由于"Strict On",我收到此错误:

Option Strict On禁止从'System.Collections.Generic.Dictionary(Of System.Collections.Generic.KeyValuePair(Of String,Integer),System.Collections.Generic.KeyValuePair(Of String,Integer))'到'System的隐式转换. Collections.Generic.IDictionary(Of String,Integer)'

我怎么解决这个问题?

jas*_*son 8

这将是有效的,即使有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)
Run Code Online (Sandbox Code Playgroud)

问题就在于您的代码:

ToDictionary(Of List(Of KeyValuePair(Of String, Int32)))
Run Code Online (Sandbox Code Playgroud)