我正在尝试创建一个 In
和 NotIn
表达式操作或本质上扩展 System.Linq.Expressions.Expression
以具有以下能力检查属性值是否在属性值列表的数组中,但我不知道这是否可能。
我正在阅读 this article它说“无法执行一系列任意操作”。我不知道是否有可能创建这些新操作或从哪里开始。任何帮助或提示将不胜感激。
public static BinaryExpression MakeBinary(
ExpressionType binaryType,
Expression left,
Expression right)
最佳答案
您可以只调用 Enumerable.Contains
方法。
static Expression<Func<IEnumerable<string>, bool>> containsExpr = en => en.Contains(null);
static MethodInfo containsMethodInfo = ((MethodCallExpression)containsExpr.Body).Method.GetGenericMethodDefinition();
public static Expression In(this Expression value, Expression arrayOfValues)
{
return Expression.Call(containsMethodInfo.MakeGenericMethod(arrayOfValues.Type.GetElementType()),
arrayOfValues, value);
}
public static Expression NotIn(this Expression value, Expression arrayOfValues)
{
return Expression.Not(In(value, arrayOfValues));
}
然后你可以这样调用它:
public class Foo { public int FooValue { get; set; } }
public void ExpressionInArray()
{
var propertyReference = MemberExpression.Property(Expression.Constant(new Foo() { FooValue = 3 }), "FooValue");
var validValues = Expression.Constant(new[] { 3, 4, 5 });
var invalidValues = Expression.Constant(new[] { 6, 7, 8 });
var expressionEvaluatingToTrue = propertyReference.In(validValues);
var expressionEvaluatingToFalse = propertyReference.In(invalidValues);
var expressionEvaluatingToTrue2 = propertyReference.NotIn(invalidValues);
var expressionEvaluatingToFalse2 = propertyReference.NotIn(validValues);
}
假设类型是一个数组而不是任何旧的 IEnumerable<T>
.如果你必须采取任何旧IEnumerable<T>
, 你必须改变 arrayOfValues.Type.GetElementType()
需要 arrayOfValues.Type
的东西并找到合适的 IEnumerable<T>
实现并从该接口(interface)返回通用参数。
关于c# - 在System.Linq.Expressions.Expression中加入In和NotIn,可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889184/