Dynamic Linq allows you to change the order of expressions at runtime.

c# dynamic-linq

Question

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?

1
2
5/3/2013 1:10:48 AM

Accepted Answer

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 + "."));
3
5/3/2013 1:10:55 AM

Popular Answer

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



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow