你可以这样做:
class Program
{
public enum Operator
{
And,
Or
}
public class Condition
{
public Operator Operator { get; set; }
public string FieldName { get; set; }
public object Value { get; set; }
}
public class DatabaseRow
{
public int A { get; set; }
public string B { get; set; }
}
static void Main(string[] args)
{
var conditions = new List<Condition>
{
new Condition { Operator = Operator.And, FieldName = "A", Value = 1 },
new Condition { Operator = Operator.And, FieldName = "B", Value = "Asger" },
new Condition { Operator = Operator.Or, FieldName = "A", Value = 2 },
};
var parameter = Expression.Parameter(typeof (DatabaseRow), "x");
var currentExpr = MakeExpression(conditions.First(), parameter);
foreach (var condition in conditions.Skip(1))
{
var nextExpr = MakeExpression(condition, parameter);
switch (condition.Operator)
{
case Operator.And:
currentExpr = Expression.And(currentExpr, nextExpr);
break;
case Operator.Or:
currentExpr = Expression.Or(currentExpr, nextExpr);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
var predicate = Expression.Lambda<Func<DatabaseRow, bool>>(currentExpr, parameter).Compile();
var input = new[]
{
new DatabaseRow {A = 1, B = "Asger"},
new DatabaseRow {A = 2, B = "Hans"},
new DatabaseRow {A = 3, B = "Grethe"}
};
var results = input.Where(predicate).ToList();
}
static BinaryExpression MakeExpression(Condition condition, ParameterExpression parameter)
{
return Expression.Equal(
Expression.MakeMemberAccess(parameter, typeof (DatabaseRow).GetMember(condition.FieldName)[0]),
Expression.Constant(condition.Value));
}
}
这假设您有一个类作为具有正确类型的数据库行的模型。然后,您可以通过正则表达式将您的条件解析为上面显示的类型条件列表,并且提供的代码可以将其转换为表达式树。生成的表达式可以编译并运行(如图所示)或转换为 SQL(只是将谓词填充到 IQueryable.Where 中)。