谓词生成器 C# 混淆
本文关键字:混淆 谓词 | 更新日期: 2023-09-27 18:37:26
我试图理解predicate builder
,以便我可以将其应用于我正在创建的Web应用程序。
基本上,我有 4 个通过 POST 请求传入的参数,"名称"、"位置"、"年龄"、"性别",我必须根据这些参数从数据库表中过滤掉人员。
问题是,每个参数都有可能是"全部"(意思是,如果名称="全部",这意味着不要按姓名过滤掉人,如果位置="全部"不要按位置过滤人等)。
所以我想到的一种方法是让所有人都进入一个列表,并有 4 个 if 语句:
if (name != 'All') {
//filter list of people by name string
}
if (location != 'All') {
//filter list of people by location
}
但我不想这样做,我想使用谓词生成器来构建 linq 表达式,并且只获取与参数匹配的人员列表,但我不明白谓词生成器在做什么。
这是我正在查看的网站,但它并没有真正解释正在发生的事情,我不知道如何将其应用于我的情况
也许我不明白这个问题,但你为什么不能这样做:
query = name == "All" ? query : query.Where(x => x.Name == name);
query = location == "All" ? query : query.Where(x => x.Location == location);
对于您的特殊情况,我认为您需要做的是:
var query = db.People;
query = name == "All" ? query : query.Where(x => x.Name == name);
query = location == "All" ? query : query.Where(x => x.Location == location);
query = age == "All" ? query : query.Where(x => x.Age == age);
query = weight == "All" ? query : query.Where(x => x.Weight == weight);
var results = query.ToList();
如果只有四个参数,那么我只会使用默认参数值和一个条件 Linq Where
子句。 我包括了StartsWith()
、EndsWith()
和Contains()
,以展示其他可能性。
进行了更新以阐明数据库交互发生的位置。
public class Example {
private IRepository repos;
//pass in your database context abstract here
public Example(IRepository repos){
this.repos = repos;
}
public IEnumerable<Person> PostMethod(string name = "All", string age = "All",
string height = "All", string weight = "All") {
//reference your database abstract here
return repos.People.Where(x => name == "All" || x.Name == name)
.Where(x => age == "All" || x.Age.Contains(age))
.Where(x => height == "All" || x.Height.StartsWith(height))
.Where(x => weight == "All" || x.Weight.EndsWith(weight));
}
}