簡體   English   中英

向現有的Linq查詢添加其他WHERE子句

[英]Add additional WHERE clause to existing Linq query

我有一個方法可以接受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子句,以便僅返回匹配兩者的記錄。

本示例在執行查詢之前修改查詢:

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

這可能不完全適合您的情況,但至少應該為您提供一個起點。

最后,我這樣管理它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM