Friday, April 23, 2010

Linq: Search Query that takes advantage of ?? operator to ignore the optional criteria fields

In search we often need to deal with the situations where users leave search input fields empty. Suppose user want to search customers against Last Name and Birth Year. The code snippet below shows the C# Search query; it works even if user leaves Criteria fields empty. Thanks to new ?? Null Comparison Operator....if the value of Criteria Field is null then the value proceeding ?? is replaced with the actual value...

public List Search( Criteria criteria )
var customers= from c in dataContext.Cutomers
where
(criteria.LastName?? c.LastName) == c.LastName
&& ( criteria.Year ?? 1980 ) <= c.BirthYear
select c;

return c.ToList();
}