谓词构建器无法正常工作

时间:2016-02-02 21:05:20

标签: c# asp.net predicatebuilder

我不确定为什么这段代码不会编译。任何帮助将不胜感激。我正试图遵循这个SO thread

List<AgeRange> ageRanges = new List<AgeRange>();
List<Person> people = new List<Person>(); 

protected void Page_Load(object sender, EventArgs e)
{
    ageRanges.Add( new AgeRange {Min = 10, Max = 15 });
    ageRanges.Add( new AgeRange {Min = 20, Max = 25 });

    for (var i = 1; i <= 25; i++)
    {
        people.Add(new Person { Age = i });
    }

    var agePredicate = BuildAgePredicate(ageRanges);
    var result = people.Where(agePredicate);
}

static Expression<Func<Person, bool>> BuildAgePredicate(IEnumerable<AgeRange> ranges)
{
    var predicate = PredicateBuilder.False<Person>();
    foreach (var r in ranges)
    {
        // To avoid capturing the loop variable
        var r2 = r;
        predicate = predicate.Or(p => p.Age >= r2.Min && p.Age <= r2.Max);
    }
    return predicate;
}

0 个答案:

没有答案