VB中Arraylists的交集

时间:2022-08-13 22:51:00

I've a legacy code base where I've four ArraysLists (different sizes). I want to compare these four arraylists and save the same values in a separate Array/Arraylist.

我有一个遗留代码库,我有四个ArraysLists(不同大小)。我想比较这四个arraylists并将相同的值保存在一个单独的Array / Arraylist中。

The arrays can have same values multiple times since ordering is not important. You can say that I just need the intersection of the ArrayLists.

由于排序不重要,因此阵列可以多次具有相同的值。你可以说我只需要ArrayLists的交集。

The following code works, but of-course this is not the best way to do, looping on all the arrays-

以下代码有效,但当然这不是最好的方法,循环所有数组 -

For i = 0 To arr.Count - 1 Step 1
   For j = 0 To arr1.Count - 1 Step 1
       If arr.Item(i) = arr1.Item(j) Then
          For k = 0 To arr2.Count - 1 Step 1
              If arr.Item(i) = arr2.Item(k) Then
                 For l = 0 To arr3.Count - 1 Step 1
                     If arr.Item(i) = arr3.Item(l) Then
                        // the value arr.Item(i) exists in all 4 arrys
                        // save this to another array
                     End If
                 Next
              End If
          Next
        End If
     Next
Next

Since my arrayList size could be in thousands, that's not the way I want to know how should I sort out this.

由于我的arrayList大小可能是数千,这不是我想知道如何解决这个问题的方式。

Thanks.

谢谢。

PS. Sorry if this is a duplicate question, since I was not able search this anywhere (I'm new to VB).

PS。很抱歉,如果这是一个重复的问题,因为我无法在任何地方搜索(我是VB的新手)。

1 个解决方案

#1


1  

you could use ArrayList.Contains to shorten / simplify things:

你可以使用ArrayList.Contains缩短/简化事情:

For i As Integer = 0 To arr.Count - 1
     If Arr1.Contains(arr(i)) AndAlso Arr2.Contains(arr(i)) _
             AndAlso Arr3.Contains(arr(i)) AndAlso Arr4.Contains(arr(i)) Then

             // the value arr(i) exists in all 4 arrayLISTS
             // save this to another array
      End If
Next

Probably wont be a lot different in speed, but the code is sure easier to read. NB: AndAlso is important in this because it short circuits the later tests when it the result is false.

可能在速度上不会有太大的不同,但代码肯定更容易阅读。注意:并且在这方面也很重要,因为当结果为假时,它会使后来的测试短路。

#1


1  

you could use ArrayList.Contains to shorten / simplify things:

你可以使用ArrayList.Contains缩短/简化事情:

For i As Integer = 0 To arr.Count - 1
     If Arr1.Contains(arr(i)) AndAlso Arr2.Contains(arr(i)) _
             AndAlso Arr3.Contains(arr(i)) AndAlso Arr4.Contains(arr(i)) Then

             // the value arr(i) exists in all 4 arrayLISTS
             // save this to another array
      End If
Next

Probably wont be a lot different in speed, but the code is sure easier to read. NB: AndAlso is important in this because it short circuits the later tests when it the result is false.

可能在速度上不会有太大的不同,但代码肯定更容易阅读。注意:并且在这方面也很重要,因为当结果为假时,它会使后来的测试短路。