Create and add Indexes

Lets assume that we have Person class as below :
public class Person
    public long Id { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string NationalNo { get; set; }
    public DateTime BirthDate { get; set; }

And we have many Person objects that we want to filtering on them many times.

We have 2 default Index implementations in this library :
ListIndex<T> and UniqueListIndex<T> ,
for field or combination of fields that should be unique in the list its better to use UniqueListIndex<T>, it performs better and also it will grantee that the filed or combination of fields are unique.
We will use IndexedList in this page for explanations.
First you should create an IndexedList to store this Person objects there,
IIndexedList<Person> People = new IndexedList<Person>();

Then you should create your indexes (You can add indexes later too).

An index needs 2 things to know.
1)The Type of object that should be indexed.
2)The fields that should be indexed.
You can give a name to indexes too, its optional.
So you can create an index object 2 ways (name is optional parameter both ways):
//Giving the field names by expression
ListIndex<Person> index = new ListIndex<Person>(p=> new {p.Name, p.Family });

//Giving the field names manually
ListIndex<Person> index = new ListIndex<Person>(new HashSet<string>(){"Name","Family"});

Default Index names are field names separated by underscore "_" .
Then you should add index to your IndexedList:

Then you can add items to your list.

You can use AddIndex Extension method on IndexedList instances too, this method creates and add index to the IndexedList .
People.AddIndex(p=> new {p.Name, p.Family });

You can add items to the IndexedList manually or you may use Extension method ToIndexList() on IEnumerable objects like EF objects .
If you are using ToIndexList you should add the indexes after IndexedList data created
DBEntities ent = new DBEntities();
IndexedList<Person> People = ent.People.ToIndexList();

This will add index and do a reindex on all People added to the list before.

Last edited Oct 15, 2013 at 2:39 PM by Basir_ansary, version 9