Linq Where() func with multple filters. Results wrong result

142 Views Asked by At

I am tring to put multple condition in where clause but not getting result as exprected.

what i am doing. in (LinqPad)

void Main()
{
    var lst = new List<Employee>()
    {
     new Employee() { Name="Name1", Address="address1",Desig="Desig1"}, 
     new Employee() { Name="Name2", Address="address2",Desig="Desig2"}, 
     new Employee() { Name="Name3", Address="address3",Desig="Desig3"}, 
     new Employee() { Name="Name4", Address="address4",Desig="Desig4"},
     new Employee() { Name="Name5", Address="address5",Desig="Desig5"},
     new Employee() { Name="Name6", Address="",Desig=""},
     new Employee() { Name="", Address="",Desig="Desig4"},
     new Employee() { Name="Name8", Address="address4",Desig=""}     
    };

var query =     (from d in lst
                select d).ToList();


var filter =query.Where(x=> !string.IsNullOrWhiteSpace(x.Name) && !string.IsNullOrWhiteSpace(x.Address)).ToList();              

filter.Dump();
}

// Define other methods and classes here
public class Employee
{
 public string Name {get;set;}
 public string Address {get;set;}
 public string Desig {get;set;}
}

Expected result is show the items where Name and Address are not null. but getting wrong result. which check whether Name or Address Is not null.

Result as 
    Name1   address1    Desig1
    Name2   address2    Desig2
    Name3   address3    Desig3
    Name4   address4    Desig4
    Name5   address5    Desig5
    Name8   address4    

Expected Result

    Name1   address1    Desig1
    Name2   address2    Desig2
    Name3   address3    Desig3
    Name4   address4    Desig4
    Name5   address5    Desig5
    Name6       
    Name8   address4    

It seems like Where condition only parse one condition at a time. thus both of these condition treeted as Or Condition.

1

There are 1 best solutions below

2
On BEST ANSWER

Ok, after your edit your question is now clear.

The problem is that you are using a conditional AND && in your query. If the first operand is false, then the second isn't evaluated because the result is always false since both operands must evaluate to true.

What you are doing is checking for null/empty/whitespace on both address and name.

Which is why the record:

  new Employee() { Name="Name6", Address="",Desig=""},

Is not appearing in your expected output. Name is not null/empty but Address is so the statement returns false and it is not included.

You query should be:

var filter = query.Where(x => !string.IsNullOrWhiteSpace(x.Name)
             || !string.IsNullOrWhiteSpace(x.Address)).ToList();  

Conditional OR will ensure that if either one of the two operands evaluates to true, then the whole statement is true.

If the first operand is true, then the second isn't evaluated a.k.a "short circuit evaluation".