Sam
Sam

Reputation: 4339

Chaining multiple Linq Where calls as an OR, not an AND

I have filtering code that I am refactoring that presently has a large number of IF blocks to determine the way to apply a filter.

It currently looks at the various options for filters and builds one big Linq (to EF) statement that does everything.

When you chain multiple Linq .Where calls, the resultant operation is an AND. How do you do an OR when chaining multiple .Where calls.

For example

users = users.Where(l => l.Location == "MyLocation")
users = users.Where(r => r.Role == "Role")

The result would be the same as

users = users.Where(u => u.Location == "MyLocation" && u.Role == "Role")

Where I want

users = users.Where(u => u.Location == "MyLocation" || u.Role == "Role")

Thanks.

Upvotes: 0

Views: 113

Answers (3)

SLaks
SLaks

Reputation: 887285

You're looking for PredicateBuilder, which can construct expression trees from logical operators.

Upvotes: 1

user2492798
user2492798

Reputation: 589

I use the code to execute OK. users = users.Where(u => u.Location == "MyLocation" || u.Role == "Role")

My test code is follow:

 private class User
    {
        public string Location = "MyLocation";
        public string Role = "Role";
        public string Data = "TestData";
    }
private void LinqOr()
    {
        //throw new NotImplementedException();
        IEnumerable<User> users = new User[] {
                        new User{Location="MyLocation",Role="Role",Data="Data1"},
                        new User{Location="MyLocation",Role="Role",Data="Data2"},
                        new User{Location="MyLocationB",Role="Role3",Data="Data3"},
                        new User{Location="MyLocationB",Role="Role4",Data="Data4"},
                        new User{Location="MyLocationC",Role="Role",Data="Data5"},
                        new User{Location="MyLocationC",Role="Role",Data="Data6"},
                        new User{Location="MyLocationD",Role="Role7",Data="Data7"},
        };

        //users = users.Where(l => l.Location == "MyLocation");
        //users = users.Where(R => R.Role == "Role");
        //users = users.Where(u => u.Location == "MyLocation" && u.Role == "Role");
        users = users.Where(u => u.Location == "MyLocation" || u.Role == "Role");
        string result = "";
        foreach (User user in users)
        {
            result += user.Location + " " + user.Role + " " + user.Data + "\r\n";
        }
        MessageBox.Show(result);
    }


    private void btnTest_Click(object sender, EventArgs e)
    {          
        LinqOr();
    }

Result as shown in the figure.

enter image description here

Upvotes: 0

Haney
Haney

Reputation: 34762

users = users.Where(l => l.Location == "MyLocation")
    .Union(users.Where(r => r.Role == "Role"));

Does that work for you?

Upvotes: 0

Related Questions