Integer Comparison with ArrayList

Technorati Tags:

Today I needed to compare some IDs contained in two generic lists (both lists held a different type).  I wanted to check to see if both lists had the same set of IDs.  Since both lists contained different types, I couldn’t just compare them as easily as I wanted to.  So, I created a method to just take in those types and add those IDs to 2 arrays and just compare the arrays instead.  Always a pain in the ass doing comparisons of course unless you’re using Linq.  Unfortunately at my new job, we are not using .NET 3.5 at the moment so I definitely miss that from the past, but we’ll be upgrading to .NET 3.5 or .NET 4.0 next year so won’t be long till I have my .NET 3.5 back.

So on with the code.  Here’s how I did it.  Nothing overly surprising or shocking here:

Note:  OrderItemList & ProductItemList implement List<OrderItem> and List<ProductItem> therefore they are generic lists of those types incoming to the method.

   1: protected bool ItemsListIsTheSame(OrderItemList orderItemList, ProductItemList productItemList)
   2: {
   3:     if(orderItemList == null || productItemList == null)
   4:       return false;
   5:         
   6:     bool result = false;
   7:  
   8:     // Initialize array length to the generic list sizes
   9:     int[] productItemIDs = new int[productItemList.Count];
  10:     int[] orderItemIDs = new int[orderItemList.Count];
  11:  
  12:     // loop through generic lists & get the list of ItemIDs (int)
  13:     for (int i = 0; i < orderItemList.Count; i++)
  14:     {
  15:         productItemIDs[i] = orderItemList[i].ItemID;
  16:     }
  17:  
  18:     for (int i = 0; i < productPersList.Count; i++)
  19:     {
  20:         orderItemIDs[i] = productItemList[i].Id;
  21:     }
  22:  
  23:     if(productItemIDs == null || orderItemIDs == null)
  24:         return false;
  25:     
  26:     // sort & compare each array of IDs
  27:     if (productItemIDs.Length == orderItemIDs.Length)
  28:     {
  29:         result = true;
  30:         Array.Sort(productItemIDs);
  31:         Array.Sort(orderItemIDs);
  32:  
  33:         // note: do not perform a nested loop here, it would be inefficient
  34:         for (int i = 0; i < productItemIDs.Length; i++)
  35:         {
  36:         if (orderItemIDs[i] != productItemIDs[i])
  37:         result = false;
  38:         }
  39:     }
  40:  
  41:      return result;
  42: }

Please kick/dzone/digg if this post if it was helpful.


 
Share this post :

Print | posted on Friday, November 14, 2008 10:00 PM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
 
Please add 7 and 4 and type the answer here: