我有以下函数,该函数可以从数据库中预先获取一系列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] 删除。
我来说两句