sipsorcery
sipsorcery

Reputation: 30714

Dynamic Linq - Setting orderby expression type at runtime

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?

Upvotes: 2

Views: 2787

Answers (2)

sipsorcery
sipsorcery

Reputation: 30714

Looks like the dynamic Linq extension methods take care of it all for me. I was making it too hard.

var result = from item in table.Where("owner = \"joe\"").OrderBy("inserted") select item;
result.ToList().ForEach(m => Console.WriteLine("inserted=" + m.Inserted + "."));

Upvotes: 3

James McCormack
James McCormack

Reputation: 9954

Yeah - though one problem is that DynamicLinq won't let you sort using an IComparer. I have a solution to that.

Upvotes: 0

Related Questions