LINQ and optional parameters LINQ and optional parameters asp.net asp.net

LINQ and optional parameters


The parameters of the method could accept null values and the Where restriction could be evaluated for each not null parameter:

IQueryable<Product> q = databaseObject.Products;if (catId != null){    q = q.Where(p => p.Category == catId);}if (brandId != null){    q = q.Where(p => p.Brand == brandId);}// etc. the other parametersvar result = q.ToList();


If this is Linq To SQL:

databaseObject.Products.Where(p=> (catId == null || p.Category == catId) );

Linq To SQL, efficiently writes the SQL sent to backend without a where clause if CatId is null. You can have multiple of these constructs, and only those with a nonNull value is included in the where construct.


databaseObject.Products.Where(p=> ((catId==null) ||  (p.Category == catId)))

For your other 3 optional parameters, you can AND them in, doing your entire search in one linq statement.