Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
861 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...