C# 使用表达式类筛选实体

C# 使用表达式类筛选实体,c#,C#,我创建了个人实体 public class Person { public int Id {get;set;} public string Fullname {get;set;} public int Age {get;set;} } 所以接下来我想过滤它。所以我也为Person做了readmodel public class PersonReadModel { public Expression<Func<int, bool>> Id

我创建了个人实体

public class Person
{
    public int Id {get;set;}
    public string Fullname {get;set;}
    public int Age {get;set;}
}
所以接下来我想过滤它。所以我也为Person做了readmodel

public class PersonReadModel
{
    public Expression<Func<int, bool>> Id {get;set;}
    public Expression<Func<string, bool>> Fullname {get;set;}
    public Expression<Func<int, bool>> Age {get;set;}
}
正如你所看到的,我想过滤20岁以上、id大于100的人

问题是如何将过滤器变量应用于where子句

_personRepository.GetAll().Where(? filter variable ?)
它能做到吗?
我希望我的解释能被理解,如果不能,我很抱歉。

根据您的情况,您可以像这样直接使用
Where

var filter = _personRepository.GetAll().Where(x=>x.Id > 100 && x.Age>20);

可以在树级别组合表达式,但这确实很难-坦率地说,我只是使用
Where(yourIdFilter)。Where(yourAgeFilter)
-我不太明白
PersonReadModel
在这里做什么。。。或者这与
人的关系如何。您真正需要的是
Expression
之类的过滤器以及
p=>p.Id>100
之类的示例。你能在这里阐明
PersonReadModel
的角色吗?@marcGravel它提供了从实体到过滤器的每个属性。但我认为这将是非常困难的,因为我想做。但是我喜欢你用“Where(yourIdFilter).Where(yourAgeFilter)”这个词。但仍然不知道如何将filter.Id放入where子句。可能是_personRepository.GetAll().Where(person=>filter.Id.Invoke(person.Id)?).Where(person=>filter.Age.Invoke(person.Age)?@syyl您的意思可能是:
public Expression ById(int Id)=>p=>p.Id>Id?您发布的表达式没有真正意义-它需要是一个过滤
Person
instances@MarcGravell这就是我所说的。@MarcGravell
public Expression ById(Func id)=>p=>id.Invoke(p.id)
list.Where(filter.ById(id=>id==1 | | id==2.Compile())
是的,这是个好主意。非常感谢。我的最后一个问题是它是在SQL(IQueryable)还是在编译程序(Enumerable)中使用实体
var filter = _personRepository.GetAll().Where(x=>x.Id > 100 && x.Age>20);