Cags Posted December 9, 2005 Posted December 9, 2005 Say I have the following... 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? 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. Quote Anybody looking for a graduate programmer (Midlands, England)?
IngisKahn Posted December 9, 2005 Posted December 9, 2005 What you're looking for is a set. PowerCollections should solve your problems. :) http://www.wintellect.com/powercollections/ Quote "Who is John Galt?"
Leaders Iceplug Posted December 17, 2005 Leaders Posted December 17, 2005 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). Quote Iceplug, USN One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.