.net 使用.ToDictionary将(KeyValuePair的列表(字符串的,Int32)转换为(字符串的,Int32)字典

.net 使用.ToDictionary将(KeyValuePair的列表(字符串的,Int32)转换为(字符串的,Int32)字典,.net,vb.net,list,sorting,todictionary,.net,Vb.net,List,Sorting,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

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

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方法将列表对象转换回目录对象时,我在“pair.Key”上得到一个错误,它说:

“字符串”类型的值无法转换为“System.Collections.Generic.List(属于System.Collections.Generic.KeyValuePair(属于字符串,属于整数))

如何使用.ToDictionary从对象列表中获取Dictionary对象

如果使用.ToDictionary方法将行更改为:

idCurrentJobs = jobsSortedByCount.ToDictionary(Of KeyValuePair(Of String, Int32))(Function(pair As KeyValuePair(Of String, Int32)) pair)
我之所以出现此错误是因为“严格限制”:

选项Strict On不允许隐式 从 'System.Collections.Generic.Dictionary(Of System.Collections.Generic.KeyValuePair(共个) 字符串,整数), System.Collections.Generic.KeyValuePair(共个) 字符串,整数)),以 'System.Collections.Generic.IDictionary(Of 字符串,整数)'

我如何解决这个问题?

试试:

idCurrentJobs = jobsSortedByCount.ToDictionary(Of String, Int32)(Function(p) p.Key, Function(p) p.Value)

即使对选项有严格限制,这也会起作用

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)))

非常感谢!但是为什么每个人在使用Function()时都包含字母“p”,它有什么意义吗?不,它只是一个名称;你可以随意调用它。是的,但是为什么是“p”?:)如果我想尽可能清楚的话,我应该给它起什么名字?
p
。我喜欢lambda表达式中变量的短名称。我见过
p
用于
KeyValuePairs
,我想它代表参数:)