Warm tip: This article is reproduced from stackoverflow.com, please click
vb.net key-value

How do I get the value from a specific Key with Key Value Pair and VB.Net?

发布于 2020-04-04 10:11:25
Public _SecurityLevel As List(Of KeyValuePair(Of Integer, Integer))

Public Sub New()
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(1, 0))
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(2, 1))
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(3, 2))
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(4, 3))
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(5, 4))
    _SecurityLevel.Add(New KeyValuePair(Of Integer, Integer)(6, 5))
End Sub

I want to get the value (3) when I specify the Key (4).

I don't want to iterate through the entire KVP until I find it.

Is this possible? If not what should I be using?

Questioner
software is fun
Viewed
72
Mary 2020-02-01 08:01

A Dictionary seems more appropriate for your application.

Public Class SomeClass
    Public _SecurityLevel As New Dictionary(Of Integer, Integer)

    Public Sub New()
        _SecurityLevel.Add(1, 0)
        _SecurityLevel.Add(2, 1)
        _SecurityLevel.Add(3, 2)
        _SecurityLevel.Add(4, 3)
        _SecurityLevel.Add(5, 4)
        _SecurityLevel.Add(6, 5)
    End Sub
End Class

Private Sub OPCode()
    Dim sc As New SomeClass
    Dim v = sc._SecurityLevel(4)
    Debug.Print(v.ToString)
    'Prints 3
End Sub

It would be unusual to have a public field in a class.