user2548530
user2548530

Reputation: 13

Dynamic Linq Sort not working for ArrayList

I am trying to do something like the following

string orderedBy = "item.length";

    var sorted = from PPart item in partList
                 orderby orderedBy
                 select item;

where partList is an array list containing PPart type objects. The above statement is not sorting the arrayList.

If i write the item.length directly in the linq query, something like below, then the list is sorting

 var sorted = from PPart item in partList
                             orderby item.length
                             select item;

How can i make dynamic linq to work with late binding

Upvotes: 0

Views: 145

Answers (1)

user5147454
user5147454

Reputation:

You could do that using Expression Trees, for example:

    public static Func<PPart, IComparable> GetOrderByPropertyExpression(string propertyName)
    {
        ParameterExpression parameter = Expression.Parameter(typeof (PPart));
        PropertyInfo baseProperty = typeof (PPart).GetProperty(propertyName);
        Expression memberExpression = Expression.Property(parameter, baseProperty);

        return
            Expression.Lambda<Func<PPart, IComparable>>(Expression.TypeAs(memberExpression, typeof (IComparable)),
                                                        parameter).Compile();
    }

And use it as following:

IOrderedEnumerable<PPart> ordered = partList.OrderBy(PPart.GetOrderByPropertyExpression("length"));

No error-checking provided, just a concept.

Upvotes: 1

Related Questions