动态 Linq - 在运行时设置 orderby 表达式类型
我正在使用动态 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 的类型?
I'm using dynamic Linq and have the where clauses working. Now I'm looking to add orderby clauses but am having a problem being able to set the type of the dynamic expression. Below is working code that I have:
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 + "."));
Because I need to use different properties in the orderby expression what I'd like to be able to do is use something like the code below which is not working.
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 + "."));
The compiler isn't happy with the line delcaring the orderExpression. Is there any way to set the type of a Func at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来动态 Linq 扩展方法为我处理了这一切。 我太难了。
Looks like the dynamic Linq extension methods take care of it all for me. I was making it too hard.
是的 - 尽管有一个问题是 DynamicLinq 不允许您使用 IComparer 进行排序。 我有一个解决方案。
Yeah - though one problem is that DynamicLinq won't let you sort using an IComparer. I have a solution to that.