我正在使用动态 Linq 并让 where 子句起作用。现在我正在寻找添加 orderby 子句,但无法设置动态表达式的类型。以下是我拥有的工作代码:
class MyClass {
public string Owner;
public DateTime Inserted;
}
Expression<Func<MyClass, bool>> whereExpression = DynamicExpression.ParseLambda<MyClass, bool>("owner = \"joe\"");
Expression<Func<MyClass, DateTime>> orderExpression = DynamicExpression.ParseLambda<MyClass, DateTime>("inserted");
var result = from item in table.Where(whereExpression).OrderBy(orderExpression) select item;
result.ToList().ForEach(m => Console.WriteLine("inserted=" + m.Inserted + "."));
因为我需要在 orderby 表达式中使用不同的属性,所以我希望能够使用类似下面的代码这样的东西,它不起作用。
Expression<Func<MyClass, bool>> whereExpression = DynamicExpression.ParseLambda<MyClass, bool>("owner = \"joe\"");
Type orderType = typeof(DateTime);
Expression<Func<MyClass, orderType>> orderExpression = DynamicExpression.ParseLambda<MyClass, orderType>("inserted");
var result = from item in table.Where(whereExpression).OrderBy(orderExpression) select item;
result.ToList().ForEach(m => Console.WriteLine("inserted=" + m.Inserted + "."));
编译器对删除 orderExpression 的行不满意。有没有办法在运行时设置 Func 的类型?