Showing posts with label Linq Optional Parameters. Show all posts
Showing posts with label Linq Optional Parameters. Show all posts

Saturday, April 03, 2010

Linq Queries with optional parameters

So i'm doing some work with Telerik OpenAccess and I had the task to write a query that has 6 parameters and the need for any combination of those parameters to be the criteria.

So here's what I did

IQueryable personQuery;

personQuery = from obj in ObjectScope.Extent()
select obj;

if (firstName != null)
personQuery = personQuery.Where(person => person.FirstName == firstName);

if (lastName != null)
personQuery = personQuery.Where(person => person.LastName == lastName);

if (middleName != null)
personQuery = personQuery.Where(person => person.MiddleName == middleName);

if (ssn != null)
personQuery = personQuery.Where(person => person.SSN == ssn);

if (city != null)
personQuery = personQuery.Where(person => person.CurrentAddress.City == city);

IList personList = personQuery.ToList();

This is the easy way to do it. I'll show you more advanced ways later.