LINQ Dynamic Query

LINQ dynamic query code

//Input : str=> string to search some text (First Name,Last Name,Date of Birth(dd/mm/yyyy) or post code) in any order;

//output : result set

str = str.ToLower().Replace("  ", " ").Trim();
IList<vw_patient> patients = App.Patients;
string[] parts = str.Split(" ".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
Func<vw_patient, bool> predicate = null;

foreach (string part in parts)
{
    long retCode = 0;
    predicate = delegate(vw_patient p)
    {
        return p.Pati_FirstName.ToLower().StartsWith(part) ||
               p.Pati_SurName.ToLower().StartsWith(part) ||
               (long.TryParse(part.Replace("/", ""), out retCode) ? ((p.Pati_DOB.HasValue ? p.Pati_DOB.Value.ToShortDateString().Replace("/", "") : "").Contains(part.Replace("/", ""))) : false) ||
               p.Pati_PostCode.Replace(" ","").ToLower().StartsWith(part);
    };
    patients =  patients.Where<vw_patient>(predicate).ToList();
}

this.dgPatients.ItemsSource = new PagedCollectionView(patients);
//PagedCollectionView is used for paging with data grid

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s