C# 向现有Linq查询添加额外的WHERE子句
我有一个接受linq查询的方法:C# 向现有Linq查询添加额外的WHERE子句,c#,linq,C#,Linq,我有一个接受linq查询的方法: public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query) { return GetAllDTO(query); } public IEnumerable GetAll(System.Linq.Expressions.Expression查询) { 返回GetAllDTO(查询);
public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query)
{
return GetAllDTO(query);
}
public IEnumerable GetAll(System.Linq.Expressions.Expression查询)
{
返回GetAllDTO(查询);
}
我希望能够在现有查询中附加一个WHERE子句,使其看起来像这样:
public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query)
{
return GetAllDTO(query).Where(x => x.Organisation == "something")
}
public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query)
{
var prefix = query.Compile();
query = c => prefix(c) && c.Organisation == organisationID;
}
public IEnumerable GetAll(System.Linq.Expressions.Expression查询)
{
返回GetAllDTO(查询)。其中(x=>x.organization==“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);
}
以及GetAllInt
方法:
private static IEnumerable<int> GetAllInt(Expression<Func<int, bool>> query)
{
return TheList.Where(query.Compile());
}
这可能不完全适合你的情况,但至少应该给你一个起点。最后我是这样处理的:
public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query)
{
return GetAllDTO(query).Where(x => x.Organisation == "something")
}
public IEnumerable<User> GetAll(System.Linq.Expressions.Expression<Func<UserDTO, bool>> query)
{
var prefix = query.Compile();
query = c => prefix(c) && c.Organisation == organisationID;
}
public IEnumerable GetAll(System.Linq.Expressions.Expression查询)
{
var prefix=query.Compile();
查询=c=>前缀(c)和&c。组织==组织ID;
}
不要修改GetAllDTO(…)
的结果。在调用方法之前修改查询
。