Reputation: 65
Well I dont realy know if this is a 2 dimensional list but I will ask anyway.
So I have this:
Dim list = New List(Of KeyValuePair(Of String, Integer))
list.Add(New KeyValuePair(Of String, Integer)("Tony", 16))
list.Add(New KeyValuePair(Of String, Integer)("George", 19))
How can i get just the value from "Tony" ? or "George"?
Upvotes: 0
Views: 2209
Reputation: 1
I suggest to use dictionary of KeyValue pair instead of List of KeyValue pair.You will have an advantage that you can check whether a key exists without iterating dictionary. If key exists you can get its value. Here's how you can do it.
Dim dict As New Dictionary(Of String, Integer)
Dim keyvalue As Integer=0
dict.Add("Jhon",47)
dict.Add("Zara",21)
if(dict.ContainsKey("Jhon")){
keyvalue = dict("Jhon")
}
While for List you will have to iterate until you find key.
Upvotes: 0
Reputation: 43743
No, that's not really what people mean when they refer to a 2D array. It's just a list of objects where each object has multiple properties. In any case, typically KeyValuePair
objects are used in Dictionary
lists rather than a simple List(Of T)
list. Since the Dictionary
object is implemented as a hash-table, it makes it very easy and efficient to access the items via their key value (i.e. name). So, for instance, if you used a dictionary like this:
Dim dict As New Dictionary(Of String, Integer)()
dict.Add("Tony", 16)
dict.Add("George", 19)
Then you could access the "Tony" item like this:
Dim age As Integer = dict("Tony")
But if you must use a List(Of KeyValuePar)
objects, then you would just need to loop through them to find the matching item, like this:
Dim match As KeyValuePair = Nothing
For Each i As KeyValuePair In list
If i.Key = "Tony" Then
match = i
Exit For
End If
Next
Dim age As Integer = match.Value
But LINQ does make that a bit easier:
Dim age As Integer = list.First(Function(x) x.Key = "Tony").Value
Upvotes: 2
Reputation: 536
list.Item(0).Key
will get the key "Tony"
list.Item(0).Value
will get the value 16
and
list.Item(1).Key
will get the key "George"
list.Item(1).Value
will get the value 19
Upvotes: 0