【问题标题】:Add additional WHERE clause to existing Linq query向现有的 Linq 查询添加额外的 WHERE 子句
【发布时间】:2014-10-29 02:39:28
【问题描述】:

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

【问题讨论】:

标签: c# linq


【解决方案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 =&gt; x != 5 开头,则上面的函数将返回x =&gt; (x != 5) &amp;&amp; (x &gt; 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

这可能不完全适合您的情况,但至少应该为您提供一个起点。

【讨论】:

    【解决方案2】:

    最后我是这样管理的:

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

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 2021-02-03
      • 2011-05-30
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多