0

我试图比较 2 ArrayLists 但没有成功。

我所拥有的是:

Dim array_1 As New ArrayList()
Dim array_2 As New ArrayList()
Dim final_array As New ArrayList()

在我有array_1array_2

array_1({10, 20}, {11, 25}, {12, 10})
array_2({10, 10}, {11, 20})

final_array想得到:

array_1(1) - array_2(1)

得到这个:

final_array({10, 10}, {11, 5}, {12, 10}

如何创建代码来正确执行此操作?这是我的尝试:

For Each element In array_1
    For Each element_2 In array_2
        If element(0) = element_2(0) Then
            final_array.Add({element(0), element(1) - element_2(1)})
        Else
            final_array.Add({element(0), element(1)})
        End If
    Next
Next

这段代码不符合我的要求。

4

2 回答 2

0

您可以使用 except LINQ 函数:

来自 MSDN

    ' Create two arrays of doubles. 
    Dim numbers1() As Double = {2.0, 2.1, 2.2, 2.3, 2.4, 2.5}
    Dim numbers2() As Double = {2.2}

    ' Select the elements from the first array that are not 
    ' in the second array. 
    Dim onlyInFirstSet As IEnumerable(Of Double) = numbers1.Except(numbers2)

    Dim output As New System.Text.StringBuilder
    For Each number As Double In onlyInFirstSet
        output.AppendLine(number)
    Next 

    ' Display the output.
    MsgBox(output.ToString())

    ' This code produces the following output: 
    ' 
    ' 2 
    ' 2.1 
    ' 2.3 
    ' 2.4 
    ' 2.5
于 2013-05-09T12:44:03.077 回答
0

你不应该像那样加入两个数组。基本上,对于第一个数组中的每个元素,您迭代整个第二个数组。

所以,在伪代码中(对不起,我的 VB 技能很糟糕)应该是这样的:

let end = min(array1.lenght, array2.length)
for i = 0 to end
  if array1[i].first = array2[i].first
  then final_array[i] = {array1[i].first, array1[i].second - array2[i].second}
  else final_array[i] = array1[i]

// in case array1 is bigger than array2 you need to copy its last elements
for j = i to array1.length
  final_array[j] = array1[j]
于 2013-05-09T11:23:36.697 回答