LINQ where filtering conditions

String Sex = getSex(); // return M or F
String[] members = getMembers(); // return member codes in array or null
//if members array is null, no filtering for member codes
var query = from tb in MemberTable
            where tb.sex.Equals(Sex) && 
                  (members != null ? members.Contains(tb.membercode) : true)
            select tb;

The code does not return the correct result. It returns all members no matter what members[].

Actually, the original LINQ is complicated, so if there are other possible solutions, I don't want to write the following:

if (members == null){ /*LINQ1*/ }
else { /*LINQ2*/ }

which is not a good coding style. Any suggestion to solve this problem?

+4
source share
2 answers
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 one.

+9
source

Since there is a short circuit ||, you must do this:

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

A subexpression (members == null || members.Contains(tb.membercode))will be true, if membersequal null, therefore Containsit will not be evaluated.

+2
source

All Articles