I created this library because I had a program that stored many objects that needed to be accessed based on one of its property values. For example, if we have a Customer class with the Properties CustomerID, FirstName, and LastName, then imagine a Customer Managment program that would keep all the customers loaded into memory.
One of the options of the program may be to “Find Customers With Last Name ____.” To accomplish this, you would loop over all the Customers you have stored in memory and find the one with the correct last name. Now if you wanted to speed this process up, you would use a Dictionary> collection and use the LastName as your key. Where this approach starts to get hard is when you want to index CustomerID and FirstName too (or any other property). Now you would have 3 dictionary collections you have to maintain. Every time you add a new customer, that’s 3 dictionaries you would have to properly add it too. Each time one of those properties was updated, you would have to update the proper collection. That really sucks…
With this library, you simply put an attribute over the property you want to make available for indexing (don’t do it for all of them, this does add a bit of overhead for each one). The attribute is aptly named [Indexable(bool isPrimary)]. The isPrimary can be set to true for one property…this basically makes it a “default” property.
You will also need to implement the IIndexedObject interface. It is just an event you have to implement. If you aren’t already inheriting from something else, you can use the IndexedObject base class that defines the method “OnPropertyChanged” for you that will in turn call the event. In your property setters, you will want to call OnPropertyChanged. This allows the Indexed Collection to automatically update the indexes when a property changes.
Now, the IndexingCollection class is the collection class. It works just like a normal List collection with a few added methods.
// You could set the initial size and growth factor
// here if you wanted
IndexingCollection customers =
new IndexingCollection();
// if you wanted to remove all the customers with
// the last name “Smith”
customers.Remove(”LastName”, “Smith”);
// if you wanted to find all the customers with
// the last name “Smith”
Customer[] custs = customers.Find(”LastName”, “Smith”);
// if you wanted to get customer 1 (and assuming
// you set CustomerID as your primary)
Customer cust = customers.Get(1);
// or
Customer cust = customers.Get(”CustomerID”, 1);
// To get them all
Customer[] all = customers.GetAll();
// To see if it contains the customer with customerId 1
if ( customers.Contains(1) )
// or
if ( customers.Contains(”CustomerID”, 1) )
As far as performance, this is slightly slower on .Add() than a List<> would be, but much faster than looping over all items in a List<> collection to find the ones you are looking for.