Linq: how to exclude a condition if the parameter is zero

I have a table and the following query condition: if parameter A is null, take everything; if not, use it in the query. I know how to do this in 2 steps:

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

Is it possible to have the same query? Thanks

+6
source share
4 answers

What about:

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

EDIT: you can do this in one request, but still using the condition:

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

I would probably write the query as follows:

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

This is not one expression, but I think it is quite readable.

Also, this code assumes context.Obj is an IQueryable<O> (for example, you are using LINQ to SQL). If not, just use IEnumerable<O> .

+3
source

I chose

 var list = context.Obj.Where(o => A.HasValue ? oa == A : true); 
+2
source

to try

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

everything should be fine. If A is null, then "aA == A" will be ignored.

0
source

Source: https://habr.com/ru/post/897431/


All Articles