向现有Linq查询添加其他WHERE子句

时间:2014-10-27 21:58:50

标签: c# linq

我有一个接受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子句添加到原始查询中,以便只返回与两者匹配的记录。

2 个答案:

答案 0 :(得分: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);
}

如果currentQueryx => 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 :(得分:1)

最后我像这样管理它:

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