Collection and predicates search elements without cycling

Among the most useful things when you work with collections, are Search methods, allowing us to find an element inside the collection using the value of one or more of his properties as a search criteria.

These methods can be implemented both as Indexer (a property) or a specific method. The second option is necessary because often there are more properties of the same data type used to search a collection and you can implement only one indexer with a certain signature.

Let’s work through some samples to see how to use predicates:

Our Entity class, named AnagraficaAzienda, exposes the following properties:

string DescrizioneRicerca //SearchDescription
string RagioneSociale //Company name
string PartitaIva //Vat Code
string Indirizzo //Address
string CAP //Zip code
string Citta //City
string PV //State or province
int IDTipo //Type
int IDAnagrafica //Identity

To create an Indexer to search through the SearchDescription we can use the following code:

public AnagraficaAzienda this[string pDescrizioneRicerca]
{
    get
    {
        return( Find(item=>item.DescrizioneRicerca==pDescrizioneRicerca);
    }
}

to create a method to get all elements that match a regular expression we can use the following code:

public List<AnagraficaAzienda> FindWithRegEx( string pRegEx )
{
    return (FindAll(items => Regex.Match(items.RagioneSociale, pRegEx).Success));
}

to create a method that returns the data using the Vat Code (PartitaIva) we can use the following code:

public AnagraficaAzienda FindXPartitaIva(string pPartitaIva)
{
    return( Find(item=>item.PartitaIva==pPartitaIva);
}

To create a multi dimensional indexer we can use the following code

public AnagraficaAzienda this[int pIDZona, int pIDAnagrafica]
{
    get
    {
        return( Find(item=>item.IDZona==pIDZona && item.IDAnagrafica==pIDAnagrafica);
    }
}

as you can see, a Predicate allows us to use any kind of binary expression to match the entity fields with the search criteria we want to use.

Print | posted on venerdì 13 agosto 2010 17.29

Feedback

No comments posted yet.

Your comment:





 
Please add 6 and 3 and type the answer here:

Copyright © Sabrina C.

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski