在函数“person.Age> 18”中变换“Age”,“>”,“18”

时间:2011-08-12 14:06:26

标签: .net linq

我必须过滤一个对象列表。

过滤器应由用户使用逻辑OR / AND运算符组成,并使用括号进行分组。

说,像这样:

enter image description here

说,我们有对象MyPerson及其属性Prop1,Prop2等......

拥有myPersons列表后,用户可以过滤元素:比如说 Prop1 == aValue AND Prop2< otherValue OR Prop2>第三个值等...

现在,我可以从原子构建表达链(感谢来自this question的Jon Skeet),如下所示:

Func<Person, bool> isAdult = person => person.Age > 18;
Func<Person, bool> isInParis = person => person.Location == "Paris";

var adultInParis = And(isAdult, isInParis);

我现在的问题是在函数表达式“person.Age&gt; 18”中从网格“Age”,“&gt;”,“18”转换字符串,以便与另一个中的另一个链接行。

1 个答案:

答案 0 :(得分:0)

也许你正在寻找这样的东西:

class Program
{
    static void Main(string[] args)
    {
        Func<Person, bool> isInParis = BuildFunc("Location", "==", "Paris");
        Console.WriteLine(isInParis(new Person { Location = "Paris"})); // Prints true
        Console.WriteLine(isInParis(new Person { Location = "Venice"})); // Prints false
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Weight { get; set; }
        public DateTime FavouriteDay { get; set; }
        public string Location { get; set; }
    }

    private static Func<Person, bool> BuildFunc(
        string propertyName, 
        string comparisonOperator, 
        string propertyValue)
    {
        var parameter = Expression.Parameter(typeof (Person), "person");
        var property = Expression.Property(parameter, propertyName);
        var constant = Expression.Constant(propertyValue);

        Expression comparison;
        switch (comparisonOperator)
        {
            case "<":
                comparison = Expression.LessThan(property, constant);
                break;
            case ">":
                comparison = Expression.GreaterThan(property, constant);
                break;
            default:
                comparison = Expression.Equal(property, constant);
                break;
        }

        return Expression.Lambda<Func<Person, bool>>(comparison, parameter).Compile();
    }
}

希望它有所帮助!