比较两个ArrayLists

时间:2013-05-09 11:09:42

标签: .net arrays vb.net

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

我拥有的是:

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

此代码无法执行我想要的操作。

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

您可以使用LINQ功能:

From the 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