Thursday, August 20, 2009

Generic List

So I was asked today how to search a generic list. Apparently the functionality in generics is not as wide spread known as I had previously thought. Being that I do a lot generic list searching for the Amazon and eBay projects I have been working on I thought I would post a couple of simple examples on how to use what I thought was the core and most important functionality available with generics. Since I am using the same data but sending different to multiple locations, I load my relational object data into searchable generic lists.

So in this example we are using the List<>.Find method to retrieve a SINGLE item from the list matching the predicate defined in the expression. This was made much easier with the release of 3.5.

InventoryItemSubmit item = messages.Find(p => p.Sku == _sku);

In this example we are looking for a single InventoryItemSubmit by matching the SKU or unique key with a particular unique key. This method will search the entire list and find the single item, if exists, that has the sku defined second in the expression. You say why not use a lambda or LINQ query? Well in this case I will have over 500K items in the list. I found in testing that the LINQ query will often through an OutOfMemory exception with large quantities of data.

This second example:

List r = results.Rows.FindAll(p => Convert.ToInt32(p["SKU"].Value) == 320934);

uses the FindAll method to retrieve a list of objects that match the criteria. So in this case we are searching a custom result set to find all the rows with a SKU or unique id that match the id 320934.

No comments: