在 Linq to SQL 中,我有一个返回 int 的表达式,我想基于该返回 bool 值的表达式创建一个表达式。 int 可用于 OrderBy(score)
,boolean 可用于 Where(ifScore)
。我无法弄清楚如何使用分数来定义 ifScore
,希望得到一些帮助。
Expression<Func<Model, int>> score = p =>
(testList.Count() > 0 && p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0);
Expression<Func<Model, bool>> ifScore = p =>
//how to say if score > 2
最佳答案
我不确定这与 LINQ to SQL 的配合情况如何,但您可以使用 Expression.GreaterThan
创建适当的二进制表达式,然后只需创建正确的 Expression<TDelegate>
即可从那开始。
var body = Expression.GreaterThan(score.Body, Expression.Constant(2));
var ifScore = Expression.Lambda<Func<Model, bool>>(body, score.Parameters);
最终的表达式看起来像这样:
p => (( testList.Count() > 0
&& p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0 ) > 2
当然,这看起来确实有点荒谬,因为它永远不可能是真的。您确定要这样做吗?也许您真的想将它与 1
进行比较或 0
取而代之的是平等?
关于c# - 从 Int 表达式创建 bool Linq to SQL 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048176/