【问题标题】:Look up dictionary by key (VB.NET按键查找字典(VB.NET
【发布时间】:2016-04-23 04:15:55
【问题描述】:
Public Sub Add(ByVal phone As String, ByVal name As String)
    MyBase.InnerHashtable.Add(phone, name)
End Sub

'--Subroutine to extract the value from a dictionary when the key is passed as input
Public Function Item(ByVal phone As String) As String
    Return CStr(MyBase.InnerHashtable.Item(phone))
End Function

示例条目:

'--Adding key and values to the dictionary    

 myDict.Add("6812036998", "Horton")
 myDict.Add("6812036999", "Olive")

我需要帮助才能反向查找字典。鉴于key 我应该能够找到名称。但是,我下面的代码将无法正常工作,因为它是错误的。

Public Function lookupValue(ByVal name As String)
    Return CStr(MyBase.InnerHashtable.Item(name))
End Function

【问题讨论】:

  • 既然已经给出了name,为什么还要在Dictionary 中找到name。或者我想你想在给定key时找到name

标签: .net vb.net visual-studio


【解决方案1】:

值不是唯一的,所以我猜你需要使用LINQ 来获取第一个值:

Dim myValue As String = myDict.FirstOrDefault(Function(x) x.Value = "Horton").Key;

编辑:

正如 Alan Mathew 和我自己所评论的那样,请确保将 System.Linq 添加为您的项目参考之一,并将 Imports System.Linq 放入您编写上述行的文件中。

【讨论】:

  • 它不工作。说 FirstOrDefault 方法不存在。另外我需要生成一个函数。
  • @AlanMathew 已更新。以前的语法是针对 C# 的(我很抱歉)。为了使它工作,你应该去你的项目参考并添加 System.Linq,同时将 import System.Linq 放在你的 .vb 文件的顶部
  • @AlanMathew :确保将 Imports System.Linq 放在代码文件的顶部。
【解决方案2】:

你的代码的标识符是关键。但是你需要价值作为标识符。试试这个 对于您的字典中的每一行作为键值对(字符串,字符串) 如果 row.value=desiredstring 那么 你的结果=row.key 结束如果

下一个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2011-08-01
    相关资源
    最近更新 更多