Create a bool Linq to SQL Expression from an Int Expression
In Linq to SQL I have an expression that returns an int, and I want to make an expression based on that expression that returns a boolean. The int can be used for OrderBy(score)
and the boolean can be used for Where(ifScore)
. I'm unable to figure out how to use score to define ifScore
, and would appreciate some help.
Expression<Func<Model, int>> score = p =>
开发者_如何学Go (testList.Count() > 0 && p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0);
Expression<Func<Model, bool>> ifScore = p =>
//how to say if score > 2
I'm not sure how well this will play with LINQ to SQL, but you can use Expression.GreaterThan
to create the appropriate binary-expression, and then it's just a matter of creating the right Expression<TDelegate>
from that.
var body = Expression.GreaterThan(score.Body, Expression.Constant(2));
var ifScore = Expression.Lambda<Func<Model, bool>>(body, score.Parameters);
The final expression will look something like:
p => (( testList.Count() > 0
&& p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0 ) > 2
Of course, that does look a little nonsensical because it can never be true. Are you sure you intended to do this? Perhaps you really want to compare it with 1
or 0
for equality instead?
精彩评论