使用linqkit创建谓词的组合表达式。

huangapple go评论71阅读模式
英文:

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 =&gt; p.FirstName == &quot;John&quot; &amp;&amp; p.LastName == &quot;Doe&quot; &amp;&amp; ((p.Age &gt; 30 || p.Status &gt;= 10)));

I tried :

var predicate = PredicateBuilder.New&lt;Person&gt;();
var orPredicate = PredicateBuilder.New&lt;Person&gt;();

orPredicate.Or(p =&gt; p.Age &gt; 30);
orPredicate.Or(p =&gt; p.Status &gt;= 10);

Predicate.And(p =&gt; p.FirstName == &quot;John&quot;);
Predicate.And(p =&gt; p.LastName == &quot;Doe&quot;);

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>



huangapple
  • 本文由 发表于 2023年6月5日 18:13:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405403.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定