0

我有我正在重构的过滤代码,目前有大量的 IF 块来确定应用过滤器的方式。

它目前查看过滤器的各种选项,并构建一个可以完成所有操作的大型 Linq (to EF) 语句。

当您链接多个 Linq.Where调用时,结果操作是 AND。.Where链接多个调用时如何执行 OR 。

例如

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")

谢谢。

4

3 回答 3

1

您正在寻找PredicateBuilder,它可以从逻辑运算符构造表达式树。

于 2013-07-22T02:15:31.967 回答
0

我使用代码执行OK。 users = users.Where(u => u.Location == "MyLocation" || u.Role == "Role")

我的测试代码如下:

 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();
    }

结果如图所示。

在此处输入图像描述

于 2013-07-22T01:47:13.487 回答
0
users = users.Where(l => l.Location == "MyLocation")
    .Union(users.Where(r => r.Role == "Role"));

那对你有用吗?

于 2013-07-21T23:52:04.510 回答