gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:23:58 38 4
gpt4 key购买 nike

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

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”上收到错误消息:

Value of type 'String' cannot be converted to 'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, Integer))

我应该如何使用 .ToDictionary 从我的对象列表中获取字典对象?

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

idCurrentJobs = jobsSortedByCount.ToDictionary(Of KeyValuePair(Of String, Int32))(Function(pair As KeyValuePair(Of String, Int32)) pair)

我收到这个错误是因为“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)'

我该如何解决这个问题?

最佳答案

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

关于.net - 使用 .ToDictionary 将 List(Of KeyValuePair(Of String,Int32)) 转换为 Dictionary(Of String, Int32),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4078513/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com