How to create indexes

Now that we can query our collections in LiveLinq, we need to create some indexes for them, otherwise LiveLinq won't query them faster than the standard LINQ does.

Suppose we have a collection implementing IIndexedSource<Customer>, for example, like this:

 

var customers = new IndexedCollection<Customer>();

 

or like this:

 

var customers = CustomersDataTable.AsIndexed();

 

The IIndexedSource<T> interface has an Indexes collection (which is actually the only thing it has), so we use that collection to create an index like this:

 

var indexByCity = customers.Indexes.Add(x => x.City);

 

That creates an index of customers by city. Once the index is created, it will be automatically maintained on every change made to the customers collection. This maintenance comes with a performance cost. The cost is not high; index maintenance is fast and you can usually ignore it as long as you don't have too many indexes, but it may become a concern if you modify the collection very intensively.

To avoid heavy index maintenance cost, you can use the BeginUpdate/EndUpdate methods while making massive changes to a collection that has indexes attached to it, for example, while populating the collection.

This index will make queries such as

 

from c in customers where c.City == "London"

 

execute very fast because LiveLinq will use the index to go directly to the required items instead of searching for them by traversing the entire collection. Indexes can speed up many queries, not just this simple one, they can also speedup range conditions (with inequalities), joins, grouping, and other LINQ operators. See LiveLinq Query Performance: Tuning Indexing Performance for the full description of what classes of queries benefit from indexes.

Explicitly creating indexes by adding them to the collection as shown above is only needed if you want direct control over their lifetimes and/or direct access to the indexes (Index<T> objects) to use them programmatically (see How to use indexes programmatically). If all you need is to optimize a few LiveLinq queries, you can use the alternative, implicit method of creating indexes, using so called hints in LiveLinq queries. A hint .Indexed() is an extension method that can be applied to a property in a query. It does not change the value of that property; it only tells LiveLinq to create an index on that property (if possible). So, instead of creating an index by city explicitly as shown above, you could write the query like this:

 

from c in customers where c.City.Indexed() == "London"

 

That would tell LiveLinq to create an index by city if it has not been already created before. This hint does not affect the value of the property, that is, the value of c.City.Indexed() is the same as the value of c.City.


Send us comments about this topic.
Copyright © GrapeCity, inc. All rights reserved.