2014-10-27 104 views
1

我有接受LINQ查询方法:添加额外的WHERE子句现有的LINQ查询

public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query) 
{ 
    return GetAllDTO(query); 
} 

我想做什么就能做的是添加一个额外的WHERE子句这个现有的查询,所以它看起来像这样:

public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query) 
{ 
    return GetAllDTO(query).Where(x => x.Organisation == "something") 
} 

但是,这将加载所有的记录,并匹配查询,然后应用where子句。我想将where子句添加到原始查询中,以便只返回匹配两者的记录。

+0

http://stackoverflow.com/questions/1266742/how-to-append-to-an-expression – TyCobb 2014-10-27 22:03:29

+0

不要修改的结果'GetAllDTO(...)'。在调用方法之前修改'query'。 – vesan 2014-10-28 00:57:03

回答

1

本示例修改查询执行前:

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 

这可能并不完全适合您的情况,但应最起码给你一个出发点。

1

最后我管理这样的:

public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query) 
{ 
    var prefix = query.Compile(); 
    query = c => prefix(c) && c.Organisation == organisationID; 
}