LINQ - Querying an ArrayList of Objects

by Aaron 09/17/08

Background

I use ArrayList heavily to load datasets into memory to minimize database queries.  This creates huge performance increases, especially for retail oriented sites with lots of product browsing.  I had implemented sorting and searching prior to LINQ but doing this involved somewhat archaic means (IComparer, and foreach loops)

I knew there had to a better way to filter an ArrayList than using a foreach loop so I looked into the LINQ functionality.  I found this MSDN article that explained most of what I wanted.  I also wanted to put the data back into an ArrayList so I had to figure that out too.  This was very easy turns out that there is an ArrayList constructor that excepts a generic list and a LINQ query has a ToList() method. 

Example

In the example below I wanted to create a method that took an ArrayList of Product Objects and returned only the active products as an ArrayList (Product has a bool Active property):

public static ArrayList getActiveProducts(ArrayList ProductList)
{
      var query = from Product p in ProductList
      where p.Active == true
      select p;
      return new ArrayList(query.ToList());
}

This code is much cleaner and efficient than using a foreach loop to copy the matching items into a new ArrayList.  There is a bit of a learning curve with LINQ but it is a great tool because it is so flexible and works with any imaginable data-source.  By the way there are also order by statement in LINQ, so I could have re-ordered my list very easily too w/o having to extend IComparer.

Tags:
Category:

blog comments powered by Disqus