Using expression evaluator to execute dynamic LINQ

2019-09-14 21:21发布

问题:

I have a generic object with properties:

Class MyObject
{
    public Dictionary<string, Object> properties = new Dictionary<string, Object>();
    public object this[string name] { get { return properties[name]: null; }
}
List<MyObject> People= new List<MyObject>();
People.Add(new MyObject(age = 50, home = "Dublin", name = "Bob", Income = "50"));
People.Add(new MyObject(age = 45, home = "London", name = "Tim", Income = "90"));

List<MyObject> Cities= new List<MyObject>();
Cities.Add(new MyObject(City = "Dublin", Country = "IE"));
Cities.Add(new MyObject(City = "London", Country = "UK"));

I would like to be able to query these Enumerables by using Linq, but these queries are dynamic and would be in strings, e.g.

People.
Where(a["age"] > 45 && Cities.Where(b["Country"] == "IE").Contains(a["home"]).
Sum(c["Income"])

Any recommendations? I'm currently using Ncalc with lots of switch statements that call Linq code...

回答1:

Have a look at Dynamic Linq