LINQ where condition filtering
c#, linq
Solution
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.
Problem
``` 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 doesn't return correct result. It returns all members no matter what `members[]` is. Actually the original LINQ is complex so if there are any other possible solutions, I do not want to write the following: ``` if (members == null){ /*LINQ1*/ } else { /*LINQ2*/ } ``` which is not a good coding style. Any suggestion for solving this problem?