GettingStarted
GettingStarted

Reputation: 7605

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

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?

Upvotes: 0

Views: 5067

Answers (3)

Mary
Mary

Reputation: 15091

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.

Upvotes: 1

MatSnow
MatSnow

Reputation: 7517

You can get it by using LINQ:

Dim theValue As Integer = _SecurityLevel.Find(Function(kvp) kvp.Key = 4).Value

But I would recommend to use a Dictionary instead, if no duplicate keys should occur.

Dim _SecurityLevel As New Dictionary(Of Integer, Integer)           
_SecurityLevel.Add(1, 0)
_SecurityLevel.Add(2, 1)
_SecurityLevel.Add(3, 2)
_SecurityLevel.Add(4, 3)
_SecurityLevel.Add(5, 4)
_SecurityLevel.Add(6, 5)

Dim result As Integer
_SecurityLevel.TryGetValue(4, result)

Edit

As stated in the comments, FindIndex would be the better joice here, as Find will return a default KeyValuePair with key/value (0,0) if no entry is found in the list.
Something like the following would be more reliable:

Dim index As Integer = _SecurityLevel.FindIndex(Function(kvp) kvp.Key = 4)
If index > -1 Then
    MsgBox(_SecurityLevel(index).Value)
Else
    'Not found
End If

Upvotes: 3

G3nt_M3caj
G3nt_M3caj

Reputation: 2685

Try this:

Dim valueFromKey As Integer = (From currentValue In _SecurityLevel.AsEnumerable
                               Where currentValue.Key = 4
                               Select currentValue.Value).FirstOrDefault

Upvotes: 0

Related Questions