Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: how to exclude condition if parameter is null

Tags:

c#

sql

linq

I have some table and the following condition of query: if parameter A is null take all, if not, use it in the query. I know how to do that in 2 steps:

List<O> list = null;
if (A = null)
{
    list = context.Obj.Select(o => o).ToList();
}
else
{
    list = context.Obj.Where(o.A == A).ToList();
}

Is it possible to have the same as one query? Thanks

like image 689
mimic Avatar asked Sep 15 '11 22:09

mimic


4 Answers

I opted for

var list = context.Obj.Where(o => A.HasValue ? o.a == A : true);
like image 141
Mladen Mihajlovic Avatar answered Oct 26 '22 01:10

Mladen Mihajlovic


How about:

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

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();

Or you could use a conditional operator to put the query in a single statement:

var query = A is null ? context.Obj : context.Obj.Where(o => o.A == A);
var list = query.ToList();

I would personally suggest either of the latter options, as they don't require that the LINQ provider is able to optimise away the filter in the case where A is null. (I'd expect most good LINQ providers / databases to be able to do that, but I'd generally avoid specifying a filter when it's not needed.)

like image 29
Jon Skeet Avatar answered Oct 26 '22 00:10

Jon Skeet


try

context.Obj.Where(a => A != null && a.A == A).ToList()

should all be good. If A is null then 'a.A == A' will be ignored.

like image 39
Christo Avatar answered Oct 26 '22 01:10

Christo


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>.

like image 27
svick Avatar answered Oct 26 '22 00:10

svick