如何在VB.Net中为此示例添加另一个值?

时间:2015-09-15 23:05:42

标签: vb.net arraylist

如何在此示例中添加其他值/参数/变量?

Dim pricesList As New List(Of KeyValuePair(Of String, String))
pricesList.AddRange({New KeyValuePair(Of String, String)("$5", "1"),
                     New KeyValuePair(Of String, String)("$3", "2")})

For Each item As KeyValuePair(Of String, String) In pricesList
    Console.WriteLine(String.Format("Price: {0}, Value {1}", item.Key, item.Value))
Next item

所以我得到像

这样的东西
Dim pricesList As New List(Of KeyValuePair(Of String, String))
pricesList.AddRange({New KeyValuePair(Of String, String)("$5", "1","1","1"),
                     New KeyValuePair(Of String, String)("$3", "2","2","2")})

For Each item As KeyValuePair(Of String, String) In pricesList
    Console.WriteLine(String.Format("Price: {0}, Value {1}, Value {1}, Value {1}, Value {1}", item.Key, item.Value))
Next item

1 个答案:

答案 0 :(得分:0)

您无法将数组传递给String.Format,并且数组的不同元素会替换字符串中的不同参数。您可以执行以下操作。请注意,我将List (Of KeyValuePair)更改为Dictionary,因为这似乎更有意义。由于键和值似乎都是整数,您可能还想使用整数(或某种数字)值而不是字符串。

[编辑] 在回复评论时添加了一条语句,以显示使用TextBoxes中的值向“词典”添加项目的示例。

Dim pricesList As New Dictionary(Of String, String()) _
    From {{"$5", {"1", "1", "1"}}, {"$3", {"2", "2", "2"}}}

pricesList.Add(PriceTextBox.Text, {V1TextBox.Text, V2TextBox.Text, V3TextBox.Text})

For Each item As KeyValuePair(Of String, String()) In pricesList
    Console.WriteLine(String.Format("Price: {0}, Value {1}, Value {2}, Value {3}", item.Key, item.Value(0), item.Value(1), item.Value(2)))
Next item