我想像在我的.php一样 vb.net 中创建数组。 php中的代码是这样的。
$query = ".......";
$query = mssql_query($query );
$data_array = array();
while ($res4 = mssql_fetch_array($query ))
{
$ms_part_cust = $res4['ms_part_cust'];
$jmlRows = $res4['jmlRows'];
$data_array[$ms_part_cust]= $jmlRows;
}
因此,如果需要,我可以在其他中调用$data_array[$ms_part_cust]。 如果在 vb.net 呢?
您似乎指的是关联数组。VB.NET 对应的是Dictionary(Of TKey, TValue)
在您的情况下,您似乎需要一个Dictionary(Of String, String)
,其中键和值都是字符串。
Dim myDict As New Dictionary(Of String, String)
向Dictionary(Of String, String)
添加项目
为了向Dictionary
添加新项,必须调用其Add()
方法,指定键及其关联值。
myDict.Add(<key>, <value>)
'Example:
myDict.Add("User", "Visual Vincent")
如果指定的键已存在于Dictionary
,则会抛出ArgumentException
,说明指定的键已存在。
从Dictionary(Of String, String)
中删除项目
同样,为了从Dictionary
中删除项目,您可以调用其Remove()
方法。但是,这次您只需指定要删除的条目的键。
myDict.Remove(<key>)
'Example:
myDict.Remove("User")
'Removes anything with the key "User" (if present).
'For example: {"User", "Visual Vincent"}.
从Dictionary(Of String, String)
获取项目
从Dictionary
中获取项目的工作方式与在 PHP 中一样,只是您使用常规括号()
而不是方括号[]
。
这样做调用Dictionary
的基础Item
属性。
myDict(<key>)
'Example:
Dim myUser As String = myDict("User")
'Returns, if present, for example "Visual Vincent".
如果在Dictionary
中找不到您要查找的密钥,它将抛出KeyNotFoundException
。
覆盖/设置Dictionary(Of String, String)
中的现有项目
覆盖(又名设置)Dictionary
中已经存在的项目也像在 PHP 中一样完成,但再次使用括号而不是方括号。
myDict(<key>) = <value>
'Example:
myDict("User") = "John Doe"
如上所述,这也调用了基础Item
属性,如果未找到指定的键,则会抛出KeyNotFoundException
。
迭代Dictionary(Of String, String)
有两种[推荐的]方法来迭代Dictionary
。您可以:
循环访问每个键,然后使用它来获取值。
For Each Key As String In myDict.Keys Dim Value As String = myDict(Key) 'Print to console in the format of: ' [key] => [value] Console.WriteLine(Key & " => " & Value) Next
遍历每个
KeyValuePair
,包含键和值。For Each Entry As KeyValuePair(Of String, String) In myDict 'Print to console in the format of: ' [key] => [value] Console.WriteLine(Entry.Key & " => " & Entry.Value) Next
模仿 PHP
模仿 PHP 行为的唯一方法:
$myArray["myKey"] = "myValue"
。添加或覆盖项目,是创建一个单独的方法(例如扩展方法)。
该方法必须检查指定的键是否已存在。如果是这样,则应覆盖与指定键关联的值。如果键不存在,则该方法应向Dictionary
添加新项。
下面是一个扩展方法的示例(需要放在单独的代码文件中,请转到Add > New item... > Module
):
Imports System.Runtime.CompilerServices
Public Module Extensions
''' <summary>
''' Adds a new key/value-pair to the dictionary if the specified key is not present, otherwise overwrites the existing value.
''' </summary>
''' <param name="Key">The key of the item to add or overwrite in the dictionary.</param>
''' <param name="Value">The value to add or overwrite in the dictionary.</param>
''' <remarks></remarks>
<Extension()> _
Public Sub AddOrSet(Of TKey, TValue)(ByVal TargetDictionary As Dictionary(Of TKey, TValue), ByVal Key As TKey, ByVal Value As TValue)
If TargetDictionary.ContainsKey(Key) = True Then
TargetDictionary(Key) = Value
Else
TargetDictionary.Add(Key, Value)
End If
End Sub
End Module
用法:
myDict.AddOrSet(<key>, <value>)
'Example:
myDict.AddOrSet("User", "John Doe")
'Overwrites "User"'s value if the key exists, otherwise adds it as a new item (key/value-pair) to the dictionary.