谓词建构者c#confusion

时间:2015-01-14 16:10:15

标签: c# linq predicatebuilder

我正在尝试理解predicate builder,因此我可以将其应用到我正在创建的网络应用中。

基本上我有4个参数通过POST请求,“名称”,“位置”,“年龄”,“性别”进入,我必须根据这些参数从数据库表中过滤掉人员。

问题是,每个参数都有可能成为'全'(意思是,如果name ='All',这意味着不按名称过滤掉人,如果location ='All'不按位置过滤人等等...)。

所以我想到这样做的一种方法是让所有人都进入一个列表,并有4个if语句:

if (name != 'All') {
 //filter list of people by name string
}
if (location != 'All') {
 //filter list of people by location
}

但我不想这样做,我想使用谓词构建器来构建linq表达式,并且只获取匹配参数的人员列表,但我不明白谓词构建器正在做什么。

This是我正在查看的网站,但它并没有真正解释发生了什么,我不知道如何将其应用于我的情况

2 个答案:

答案 0 :(得分:3)

也许我不理解这个问题,但为什么你不能这样做:

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();

答案 1 :(得分:2)

如果只有四个参数,那么我只使用默认参数值和条件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));
    }
}