我有重构的过滤代码,目前有大量的IF块来确定应用过滤器的方法。
它目前会查看过滤器的各种选项,并构建一个可以执行所有操作的大型Linq(到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")
感谢。
答案 0 :(得分:1)
您正在寻找PredicateBuilder,它可以从逻辑运算符构造表达式树。
答案 1 :(得分:0)
users = users.Where(l => l.Location == "MyLocation")
.Union(users.Where(r => r.Role == "Role"));
这对你有用吗?
答案 2 :(得分: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();
}
结果如图所示。