Linq: how to exclude condition if parameter is null Linq: how to exclude condition if parameter is null sql sql

Linq: how to exclude condition if parameter is null


How about:

list = context.Obj.Where(o => A == null || o.A == A)                  .ToList();

EDIT: You can do it in one query but still using a condition:

IEnumerable<O> query = context.Obj;if (A != null){    query = query.Where(o => o.A == A);}var list = query.ToList();


I opted for

var list = context.Obj.Where(o => A.HasValue ? o.a == A : true);


I would probably write the query like this:

IQueryable<O> query = context.Obj;if (A != null)    query = query.Where(o => o.A == A);var list = query.ToList()

It's not one expression, but I think it's quite readable.

Also, this code assumes that context.Obj is IQueryable<O> (e.g. you are using LINQ to SQL). If that's not the case, just use IEnumerable<O>.