How to construct LambdaExpression with conversion

Posted by nerijus on Stack Overflow See other posts from Stack Overflow or by nerijus
Published on 2012-11-19T16:43:53Z Indexed on 2012/11/20 11:03 UTC
Read the original article Hit count: 358

Filed under:
|
|
|
|

I need to sort in ajax response grid by column name. Column value is number stored as a string.

Let's say some trivial class (in real-life situation there is no possibility to modify this class):

class TestObject
{
    public TestObject(string v)
    {
        this.Value = v;
    }
    public string Value { get; set; }
}

then simple test:

[Test]
public void LambdaConstructionTest()
{
   var queryable = new List<TestObject>
                   {
                       new TestObject("5"),
                       new TestObject("55"),
                       new TestObject("90"),
                       new TestObject("9"),
                       new TestObject("09"),
                       new TestObject("900"),
                   }.AsQueryable();

    var sortingColumn = "Value";

    ParameterExpression parameter = Expression.Parameter(queryable.ElementType);

    MemberExpression property = Expression.Property(parameter, sortingColumn);
    //// tried this one: var c = Expression.Convert(property, typeof(double));

        LambdaExpression lambda = Expression.Lambda(property, parameter); //// constructs: o=>o.Value

        var callExpression = Expression.Call(typeof (Double), "Parse", null, property); 

        var methodCallExpression = Expression.Call(
            typeof(Queryable),
            "OrderBy",
            new[] { queryable.ElementType, property.Type },
            queryable.Expression,
            Expression.Quote(lambda)); // works, but sorts by string values.
            //Expression.Quote(callExpression)); // getting: System.ArgumentException {"Quoted expression must be a lambda"}

        var querable =  queryable.Provider.CreateQuery<TestObject>(methodCallExpression);

        // return querable; // <- this is the return of what I need. 
}

Sorry for not being clear in my first post as @SLaks answer was correct but I do not know how to construct correct lambda expression in this case.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ