【问题标题】:Convert a List(Of KeyValuePair(Of String,Int32) into a Dictionary(Of String, Int32) using .ToDictionary使用 .ToDictionary 将 List(Of KeyValuePair(Of String,Int32) 转换为 Dictionary(Of String, Int32)
【发布时间】:2010-11-02 14:12:15
【问题描述】:

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

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(的 字符串,整数), System.Collections.Generic.KeyValuePair(的 字符串,整数))'到 'System.Collections.Generic.IDictionary(的 字符串,整数)'

我该如何解决这个问题?

【问题讨论】:

    标签: .net vb.net list sorting dictionary


    【解决方案1】:

    即使使用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)))
    

    【讨论】:

    • 非常感谢!但是为什么大家在使用Function()的时候都要加上字母“p”,是不是有什么意义呢?
    • 不,这只是一个名字;你可以随便叫它。
    • 是的,但为什么是“p”? :) 如果我想尽可能清楚,我应该给它起什么名字?
    • p 用于配对。我喜欢 lambda 表达式中变量的简称。
    • 我看到p 的用途远不止KeyValuePairs,我猜它代表参数:)
    【解决方案2】:

    试试:

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

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 2015-09-04
      • 1970-01-01
      • 2012-11-29
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多