Pang
Pang

Reputation: 532

LINQ where condition filtering

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?

Upvotes: 7

Views: 102698

Answers (3)

Priyanka Arora
Priyanka Arora

Reputation: 457

var list = new List<ModelName>();
list = ctx.MemberTable
    .Where(c => c.sex==Sex)
    .Where(c => c.membercode==true)
    .ToList();

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 4

Alexey Raga
Alexey Raga

Reputation: 7525

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.

Upvotes: 16

Related Questions