LINQ where condition filtering

var query = MemberTable.Where(x=>x.sex.Equals(Sex))

if (members != null)
     query = query.Where(x=>members.Contains(x.membercode))

//use your query
query.ToList();

OR

var query = from tb in MemberTable
        where tb.sex.Equals(Sex) && 
              (members == null || members.Contains(tb.membercode))
        select tb;

I prefer the first.


Since || short-circuits, you should be able to do this:

var query = from tb in MemberTable
    where tb.sex.Equals(Sex) && 
          (members == null || members.Contains(tb.membercode))
    select tb;

The (members == null || members.Contains(tb.membercode)) subexpression will be true if members is null, so Contains would not be evaluated.

Tags:

C#

Linq