Create array from values found in both arrays

Cags

Contributor
Joined
Feb 19, 2004
Messages
695
Location
Melton Mowbray, England
Say I have the following...

C#:
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();

arr1.AddRange(new int[] { 1,2,3,4,5,6,7,8,9 });
arr2.AddRange(new int[] { 2, 5, 7 });

I need to populate arr3 with values that are in both arr1 and arr2. I'm currently doing it with the following, does anyone know of a better way of achieving this?

C#:
for(int i = 0; i < arr1.Count; i++)
    if(arr2.Contains(arr1[i]))
        arr3.Add(arr1[i]);

Just to clarify arr3 should now contain 2, 5 and 7. As I've been typing this post I've realised that in this example arr1 is larger than arr2 so it would perhaps be prudent to loop through the smaller arr2 so I might add an if statement if nobody else can think of a better solution.
 
Well, looks like you have a pretty good solution. If the arrays are going to be sorted, then you can also use BinarySearch and check for a positive result.

And the operation you are doing is a union. It is symmetric; you do not need to check anything from both array's point of view (i.e. if arr2 contains a point in arr1 and then again check if arr1 contains a point in arr2... if arr2 didn't check for it in arr1, then the point will continue to not-exist when arr1 checks for it).
 
Back
Top