我正在寻找一种从包含Linq表达式本身的字符串创建表达式的方法。
假设以下课程:
public class Person
{
public string Name { get; set; }
public string FirstName { get; set; }
public Address[] Address { get; set; }
}
public class Address
{
public string City { get; set; }
}
可以使用以下代码生成简单表达式:
var expression = @"x.Name";
var p = Expression.Parameter(typeof(Person), "x");
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, expression);
以下示例将按预期返回Name 1
:
static void Main(string[] args)
{
var personsCollection = new List<Person>
{
new Person { Name = "Name 1", FirstName = "Firstname 1", Address = new Address { City = "City 1" } },
new Person { Name = "Name 2", FirstName = "Firstname 2", Address = new Address { City = "City 2" } }
};
var expression = @"x.Name";
var p = Expression.Parameter(typeof(Person), "x");
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, expression);
var result = e.Compile().DynamicInvoke(personsCollection[0]);
}
现在,假设我将表达式更改为投射List<T>
。
表达式将是:var expression = @"x.Address.Select(dest => new { MyCity = dest.City })";
使用以上示例代码会抛出以下异常:"Unknown identifier 'dest'"
关于如何解决这个问题的任何想法?