首页 > 解决方案 > 在 IQueryable 上应用内部表达式过滤器

问题描述

假设我有以下对象:

public class Source { public string Name; }
public class Target { public string Name; }
public class Result 
{ 
   public Source SourceObj; 
   public Target TargetObj; 
} 

现在,IQueryable<Result>从某个地方获取我想为它准备表达式过滤器,只需将目标过滤器作为表达式:Expression<Func<Target, bool>> filter。过滤器方法签名如下所示:

public Expression<Func<Result, bool>> Filter(IQueryable<Result> collection, Expression<Func<Target, bool>> targetFilter)
{ 
   in result expression: "in given collection select items where their property TargetObj satisfies targetFilter"
}

任何建议将不胜感激。谢谢

标签: c#linqlambdaexpressioniqueryable

解决方案


我不确定我是否正确理解了您的目标,但我认为这可能是您想要的。

使用 linq Select,您可以映射源集合中的元素。所以在这里我们将结果映射到目标,然后应用您的目标过滤器。

public IQueryable<Target> GetFilteredTargets(IQueryable<Result> collection, Expression<Func<Target, bool>> targetFilter)
{
    return collection.Select(result => result.Target).Where(targetFilter);
}

推荐阅读