Linq:如果参数为空,如何排除条件 [英] Linq: how to exclude condition if parameter is null

查看:269
本文介绍了Linq:如果参数为空,如何排除条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,并具有以下查询条件:如果参数A为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

推荐答案

怎么样:

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

这篇关于Linq:如果参数为空,如何排除条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆