简体   繁体   中英

Linq: how to exclude condition if parameter is null

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

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

我选择了

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> (eg you are using LINQ to SQL). If that's not the case, just use IEnumerable<O> .

try

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM