LINQ Where clause with multiple conditions

Category: .NET Tags:
June 22, 2016

The LINQ where clause is easy to use but sometimes there is confusion on how to create an expression with more than one condition. There’s two ways to do this, both are equivalent and probably generate the same, efficient code.

The first method is simply to use multiple .Where statements:

myCollection.Where(x => x.Name== "aa")
            .Where(x => x.ParentID == 2)
            .Where(x => x.Category == 35)

Alternatively, you can write the expression as:

myCollection.Where(x => x.Name== "aa"
                     && x.ParentID == 2 
                     && x.Category == 35)

Note the syntax: the lambda goes to (=>) operator only appears once at the beginning.

Actually I tend to use both; the first is easier to read but the second method is better if the expression is more complex, like:

OrgType.Where(x => (x.Name == "aa") && ( (x.ParentID == 2) || (x.ParentID == 5) ) );