从二维列表中获取值
Get a value from a 2 dimensional list
嗯,我真的不知道这是不是二维列表,但我还是会问的。
所以我有这个:
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))
我怎样才能只从 "Tony" 中获取值?或 "George"?
list.Item(0).Key
将获得密钥 "Tony"
list.Item(0).Value
将得到值 16
和
list.Item(1).Key
将获得密钥 "George"
list.Item(1).Value
将得到值 19
不,当人们提到二维数组时,这并不是他们真正的意思。它只是一个对象列表,其中每个对象都有多个属性。在任何情况下,通常 KeyValuePair
对象用于 Dictionary
列表而不是简单的 List(Of T)
列表。由于 Dictionary
对象是作为散列 table 实现的,因此通过键值(即名称)访问项目变得非常容易和高效。因此,例如,如果您使用这样的字典:
Dim dict As New Dictionary(Of String, Integer)()
dict.Add("Tony", 16)
dict.Add("George", 19)
然后您可以像这样访问 "Tony" 项目:
Dim age As Integer = dict("Tony")
但是如果你必须使用一个 List(Of KeyValuePar)
对象,那么你只需要遍历它们来找到匹配的项目,就像这样:
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
但 LINQ 确实使这更容易一些:
Dim age As Integer = list.First(Function(x) x.Key = "Tony").Value
我建议使用键值对字典而不是键值列表 pair.You 将有一个优点,你可以检查一个键是否存在而无需迭代字典。如果键存在,您可以获得它的值。这是你如何做到的。
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")
}
而对于列表,您将不得不迭代直到找到键。
嗯,我真的不知道这是不是二维列表,但我还是会问的。
所以我有这个:
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))
我怎样才能只从 "Tony" 中获取值?或 "George"?
list.Item(0).Key
将获得密钥 "Tony"
list.Item(0).Value
将得到值 16
和
list.Item(1).Key
将获得密钥 "George"
list.Item(1).Value
将得到值 19
不,当人们提到二维数组时,这并不是他们真正的意思。它只是一个对象列表,其中每个对象都有多个属性。在任何情况下,通常 KeyValuePair
对象用于 Dictionary
列表而不是简单的 List(Of T)
列表。由于 Dictionary
对象是作为散列 table 实现的,因此通过键值(即名称)访问项目变得非常容易和高效。因此,例如,如果您使用这样的字典:
Dim dict As New Dictionary(Of String, Integer)()
dict.Add("Tony", 16)
dict.Add("George", 19)
然后您可以像这样访问 "Tony" 项目:
Dim age As Integer = dict("Tony")
但是如果你必须使用一个 List(Of KeyValuePar)
对象,那么你只需要遍历它们来找到匹配的项目,就像这样:
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
但 LINQ 确实使这更容易一些:
Dim age As Integer = list.First(Function(x) x.Key = "Tony").Value
我建议使用键值对字典而不是键值列表 pair.You 将有一个优点,你可以检查一个键是否存在而无需迭代字典。如果键存在,您可以获得它的值。这是你如何做到的。
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")
}
而对于列表,您将不得不迭代直到找到键。