两个数组列表-合并以创建值

时间:2018-07-28 09:46:36

标签: vb.net

我只是无法理解这一点。 。

我正在使用Visual Studio 2017和Visual Basic来瞄准2.0 .net框架。

我有两个列表数组,一个是字符串,另一个是单个。

Dim Products As New List(Of String)

Dim Quantity As New List(Of Single)

列表的以下数据:-

Products(0)="1-1/xs":Quantity(0)=2

Products(1)="1-1/s" :Quantity(1)=3

Products(2)="1-1/m" :Quantity(2)=5

Products(3)="1-1/xs":Quantity(3)=7

Products(4)="1-1/m" :Quantity(4)=8

我需要知道如何以编程方式获得此结果:-

Products(0)="1-1/xs":Quantity(0)=9

Products(1)="1-1/s" :Quantity(1)=3

Products(2)="1-1/m" :Quantity(2)=13

结果是拿走了所有产品;然后查看具有重复项的产品(删除重复项),然后将该项目数量添加到“数量”列表中。

请有人能帮助我。 。

1 个答案:

答案 0 :(得分:2)

这里是填充字典的示例。 您将遍历数据,如果不存在新对象,请在字典中填充,并在存在时增加数量。

Dim dictionary As New Dictionary(Of String, Integer)

    ' Add two keys.
    dictionary.Add("1-1/xs", 2)
    dictionary.Add("1-1/s", 1)

    ' See if this key exists.
    If dictionary.ContainsKey("1-1/xs") Then
        ' Write value of the key.
        Dim num As Integer = dictionary.Item("1-1/xs")
        Console.WriteLine(num)
        ' Or add quantity to it
        dictionary.Item("1-1/xs") = dictionary.Item("1-1/xs") + 1
    End If

字典可以包含任何对象。因此,您可能倾向于重新考虑要存储的内容。例如,您可以存储具有几个属性(例如颜色,大小等)的Product类,并使用Product的ID(例如,sku)作为字典中的键。

例如:

Dim dictionary As New Dictionary(Of String, Product)  'where Product is a class.


Public Class Product
  Public Size as String
  Public Color as String
  Public Id as String
  'etc, etc
End Class
相关问题