1

I have a set of extension methods that allow for using magic strings in the LINQ OrderBy() methods. I know the first question will be why, but it's part of a generic repository and is there for flexibility so that strings can be sent from the UI and used directly.

I have it working if you pass in a magic string that represents a property on the main entity you are querying, but I'm having trouble making it more generic so it can handle multiple levels deep magic string. For example:

IQueryable<Contact> contacts = GetContacts();

contacts.OrderByProperty("Name"); // works great

// can't figure out how to handle this
contacts.OrderByProperty("ContactType.Name");

Here is the code that I have so far:

public static class LinqHelpers
{
    private static readonly MethodInfo OrderByMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "OrderBy" && method.GetParameters().Length == 2);
    private static readonly MethodInfo OrderByDescendingMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "OrderByDescending" && method.GetParameters().Length == 2);
    private static readonly MethodInfo ThenByMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "ThenBy" && method.GetParameters().Length == 2);
    private static readonly MethodInfo ThenByDescendingMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "ThenByDescending" && method.GetParameters().Length == 2);

    public static IOrderedQueryable<TSource> ApplyOrdering<TSource>(IQueryable<TSource> source, string propertyName, MethodInfo orderingMethod)
    {
        var parameter = Expression.Parameter(typeof(TSource), "x");
        var orderByProperty = Expression.Property(parameter, propertyName);

        var lambda = Expression.Lambda(orderByProperty, new[] { parameter });

        var genericMethod = orderingMethod.MakeGenericMethod(new[] { typeof(TSource), orderByProperty.Type });

        return (IOrderedQueryable<TSource>)genericMethod.Invoke(null, new object[] { source, lambda });
    }

    public static IOrderedQueryable<TSource> OrderByProperty<TSource>(this IQueryable<TSource> source, string propertyName)
    {
        return ApplyOrdering(source, propertyName, OrderByMethod);
    }

    public static IOrderedQueryable<TSource> OrderByDescendingProperty<TSource>(this IQueryable<TSource> source, string propertyName)
    {
        return ApplyOrdering(source, propertyName, OrderByDescendingMethod);
    }

    public static IOrderedQueryable<TSource> ThenByProperty<TSource>(this IOrderedQueryable<TSource> source, string propertyName)
    {
        return ApplyOrdering(source, propertyName, ThenByMethod);
    }

    public static IOrderedQueryable<TSource> ThenByDescendingProperty<TSource>(this IOrderedQueryable<TSource> source, string propertyName)
    {
        return ApplyOrdering(source, propertyName, ThenByDescendingMethod);
    }
}

I'm pretty sure I need to split the propertyName on the period and then use those parts to build up a more complicated Expression that involves a MemberExpression and then a Property but I'm struggling. Any help or pointing in the right direction would be appreciated.

Naser Asadi
  • 1,085
  • 16
  • 34
Jeff Treuting
  • 13,352
  • 8
  • 33
  • 46
  • 1
    This works for child properties, iirc: http://stackoverflow.com/a/233505/23354 - see the `property.Split('.');` and subsequent loop – Marc Gravell Jul 21 '13 at 07:46
  • That worked perfectly. This is definitely the answer, so I upvoted the comment since I can't mark it as the answer. Thanks. – Jeff Treuting Jul 21 '13 at 16:22

1 Answers1

2

I wrote my own predicate builder type thing a while back. I attempted to adapt the code for posting here. This returns an expression to access a property, and can be used to build up more complicated expressions - just make sure that all the components of the expression use the exact same param object instance.

This won't work as a drop in for your code. It'll will require some slight adaptations to make it work for your use I think.

This outputs param => (param.Child.IntProperty == 42).

You could use the predicate variable in a where clause. Let's say you had a List<Parent> called parents, you could call parents.Where(predicate).

public class Parent {
    public string StringProperty { get; set; }

    public Child Child { get; set; }
}

public class Child {
    public int IntProperty { get; set; }
}

internal class Program {

    private static void Main(string[] args) {
        var param = Expression.Parameter(typeof(Parent), "param");
        var accessExpression = GetAccessExpression(param, "Child.IntProperty", typeof(Parent));
        var constantExpression = Expression.Constant(42);
        var condition = Expression.Equal(accessExpression, constantExpression);
        var predicate = Expression.Lambda<Func<Parent, bool>>(condition, param);

        Console.WriteLine(predicate.ToString());
    }

    /// <summary>
    /// Returns an Expression that represents member access for the specified property on the specified type. Uses recursion
    /// to find the full expression.
    /// </summary>
    /// <param name="property">The property path.</param>
    /// <param name="type">The type that contains the first part of the property path.</param>
    /// <returns></returns>
    private static Expression GetAccessExpression(Expression param, string property, Type type) {
        if (property == null)
            throw new ArgumentNullException("property");
        if (type == null)
            throw new ArgumentNullException("type");

        string[] propPath = property.Split('.');
        var propInfo = type.GetProperty(propPath[0]);

        if (propInfo == null)
            throw new Exception(String.Format("Could not find property '{0}' on type {1}.", propPath[0], type.FullName));

        var propAccess = Expression.MakeMemberAccess(param, type.GetProperty(propPath[0]));

        if (propPath.Length > 1)
            return GetAccessExpression(propAccess, string.Join(".", propPath, 1, propPath.Length - 1), type.GetProperty(propPath[0]).PropertyType);
        else
            return propAccess;
    }
}
Steve
  • 6,085
  • 2
  • 35
  • 62