本示例修改查询执行前:
private IEnumerable<int> GetAll(Expression<Func<int, bool>> currentQuery)
{
Expression left = currentQuery.Body;
BinaryExpression right = Expression.GreaterThan(
currentQuery.Parameters[0], Expression.Constant(0));
BinaryExpression combined = Expression.AndAlso(left, right);
Expression<Func<int, bool>> final = Expression.Lambda<Func<int, bool>>(
combined, currentQuery.Parameters[0]);
return GetAllInt(final);
}
如果currentQuery
开始为x => x != 5
,上面的函数将返回x => (x != 5) && (x > 0)
。
这里的其余示例代码:
private static readonly List<int> TheList =
new List<int> { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5 };
public static void Main(string[] args)
{
Expression<Func<int, bool>> initialQuery = x => x != 5;
IEnumerable<int> result = GetAll(initialQuery);
foreach (int i in result)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
而且GetAllInt
方法:
private static IEnumerable<int> GetAllInt(Expression<Func<int, bool>> query)
{
return TheList.Where(query.Compile());
}
这会打印出:
1
2
3
4
这可能并不完全适合您的情况,但应最起码给你一个出发点。
http://stackoverflow.com/questions/1266742/how-to-append-to-an-expression – TyCobb 2014-10-27 22:03:29
不要修改的结果'GetAllDTO(...)'。在调用方法之前修改'query'。 – vesan 2014-10-28 00:57:03