如何根据List的优先级顺序查找Dictionary中最早匹配项对应的Key
问题原因
原有代码的判断逻辑完全不符合业务需求,错误点如下:
- 错误判断
ListOfValues2.ContainsKey(Row.Value):ListOfValues2的Key为行号(整数类型),Row.Value是字典存储的数值(字节类型),二者类型不匹配,该判断永远返回False - 无关判断
OrElse Row.Key = 0:该条件和匹配优先级的需求没有任何关联 - 缺少核心判断逻辑:没有判断当前字典项的Value是否等于外层循环遍历到的优先级值
修复方案
按业务逻辑调整判断条件即可,正确的实现代码如下:
Public Module Program Public Sub Main(args() As String) ' 定义优先级列表,靠前元素优先级更高 Dim priorityList As New List(Of Byte)({1, 2, 3}) ' 存储行号与对应值的字典 Dim rowValueDict As New Dictionary(Of Integer, Byte) rowValueDict.Add(100, 3) rowValueDict.Add(200, 2) rowValueDict.Add(300, 1) Dim firstMatchRow As Integer = 0 ' 按优先级从高到低遍历 For Each priorityVal In priorityList ' 遍历字典找对应值的项 For Each rowItem In rowValueDict If rowItem.Value = priorityVal Then firstMatchRow = rowItem.Key GoTo exitLoop End If Next Next exitLoop: Debug.WriteLine(firstMatchRow) ' 按优先级列表{1,2,3}此处输出为300,如果需要得到示例所述的200的输出结果,可将优先级列表调整为{2,3,1}即可符合要求 End Sub End Module
内容的提问来源于stack exchange,提问作者SSpoke
相关产品推荐
相关产品推荐

