一个仅从KeyValuePair返回值的函数

保罗·史蒂文斯

我有以下函数,该函数可以从数据库中预先获取一系列KVP,现在我想编写一个函数,该函数将Integer值作为其参数并返回匹配的String值。请问这样做的最好方法是什么?

Private Function GetReasons() As List(Of KeyValuePair(Of Integer, String))
    Dim returnValue As New List(Of KeyValuePair(Of Integer, String))
    Dim con As New SqlConnection(SCRGlobals.ConnectionString)
    Dim cmd As New SqlCommand("SELECT CODE, DESC FROM ltblDELAY", con)
    cmd.CommandType = CommandType.Text
    Try
        con.Open()
        Dim c As SqlDataReader = cmd.ExecuteReader()
        While c.Read
            returnValue.Add(New KeyValuePair(Of Integer, String)(c("CODE"), c("DESC")))
        End While
    Catch ex As Exception
        Common.LogError(ex, True, False)
    Finally
        If con.State <> ConnectionState.Closed Then
            con.Close()
        End If
    End Try
    Return returnValue
End Function
水果蝙蝠

无需编写自己的函数。

Dim l As List(Of KeyValuePair(Of Integer, String))
l = GetReasons()
Dim intKey as Integer = 1 '<-- whatever value you want to look up.
'This is your function...
Dim strValue as String = l.ToDictionary(Function(x) x.Key).Item(intKey).Value

实际上,您可以将其包装在您自己的函数中(并使它更强大):

Private Function GetValue(l As List(Of KeyValuePair(Of Integer, String)), key As Integer)
    Dim d As Dictionary(Of Integer, KeyValuePair(Of Integer, String)) = l.ToDictionary(Function(x) x.Key)
    If d.ContainsKey(key) Then
        Return d.Item(key).Value
    Else
        'Default value or error message
    End If
End Function

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python:如何仅从一个函数(使用asyncio.gather执行的多个函数)中获取返回值

PHP在返回值之前遍历一个函数

使用另一个函数返回值

仅从函数访问返回值之一

如何重复一个函数,直到它的返回值与之前的返回值匹配?

在同一个“返回值对象”中访问一个 javascript 函数

使用一个返回值?

加一个返回值?

如何优雅地创建一个返回lambda返回值或什么都不返回的函数?

如何在另一个函数中引用 2 个函数的返回值?

如何将一个函数的输入值与另一个函数的返回值进行比较?

无法分配给返回值,因为函数“operator[]”返回一个常量值

如何使用函数返回值作为PHP中另一个函数的参数?

调用另一个模拟函数时更改模拟函数的返回值

使用constexpr函数的返回值作为另一个函数的参数

将函数返回值分配为另一个函数参数

Angular 2 在启动另一个函数之前等待函数返回值

从另一个函数内的回调函数返回值

Google 表格在另一个函数中使用匹配函数的返回值

将两个返回值传递给具有一个参数的函数

在c++中使用一个函数的返回值作为另一个函数的参数

将一个函数的返回值传递给已经设置了参数的另一个函数?

使用 Python 将返回值从一个函数传递到另一个函数

将一个函数的返回值检查到另一个函数中

一个函数的返回值正常工作,第二个函数的返回值不能反映正确的值

将一个方法的返回值解析为另一个函数的两个参数?

创建一个函数以从异步查询返回值

如何有条件地选择一个聚合函数的返回值?

在另一个函数中使用返回值