英文:
Combine Expression to create a predicate with linqkit
问题
.Where(p => p.FirstName == "John" && p.LastName == "Doe" && ((p.Age > 30 || p.Status >= 10)))
;
我有这个谓词,我想使用linqkit构建它,因为谓词可以根据选项更改。
我尝试过:
var predicate = PredicateBuilder.New<Person>();
var orPredicate = PredicateBuilder.New<Person>();
orPredicate.Or(p => p.Age > 30);
orPredicate.Or(p => p.Status >= 10);
Predicate.And(p => p.FirstName == "John");
Predicate.And(p => p.LastName == "Doe");
predicate = predicate.Or(orPredicate);
myQueryable = myQueryable.Where(predicate);
当我这样做时,结果就像每个条件之间是“或”关系一样。我错过了什么吗?
谢谢!
英文:
I have this predciate, I would like build it with linqkit because the predicate can change depending of options.
.Where(p => p.FirstName == "John" && p.LastName == "Doe" && ((p.Age > 30 || p.Status >= 10)))
;
I tried :
var predicate = PredicateBuilder.New<Person>();
var orPredicate = PredicateBuilder.New<Person>();
orPredicate.Or(p => p.Age > 30);
orPredicate.Or(p => p.Status >= 10);
Predicate.And(p => p.FirstName == "John");
Predicate.And(p => p.LastName == "Doe");
predicate = predicate.Or(orPredicate);
myQueryable = myQueryable.Where(predicate);
When I do this the result is like a "Or" between each(4) conditions. Am I missed something?
Thanks,
答案1
得分: 2
查看[文档](https://github.com/scottksmith95/LINQKit#nesting-predicates)后,我认为您的代码片段可以这样修复:
```csharp
var predicate = PredicateBuilder.New<Person>();
var orPredicate = PredicateBuilder.New<Person>();
orPredicate = orPredicate.Start(p => p.Age > 30);
orPredicate = orPredicate.Or(p => p.Status >= 10);
predicate = predicate.Start(p => p.FirstName == "John");
predicate = predicate.And(p => p.LastName == "Doe");
predicate = predicate.And(orPredicate);
myQueryable = myQueryable.Where(predicate);
请注意,我对LinqKit毫无经验,仅根据引用的文档提出了这些建议。
<details>
<summary>英文:</summary>
Looking at the (https://github.com/scottksmith95/LINQKit#nesting-predicates), I think your snippet can be fixed like so:
var predicate = PredicateBuilder.New<Person>();
var orPredicate = PredicateBuilder.New<Person>();
orPredicate = orPredicate.Start(p => p.Age > 30);
orPredicate = orPredicate.Or(p => p.Status >= 10);
predicate = predicate.Start(p => p.FirstName == "John");
predicate = predicate.And(p => p.LastName == "Doe");
predicate = predicate.And(orPredicate);
myQueryable = myQueryable.Where(predicate);
Mind that I have Zero experience with LinqKit and derived this just from referenced docs.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论