I am trying to write some dynamic linq to order by a property of a list item, for use with NHibernate
public class Company
{
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public string Name{get; set;}
public string PayrollNo{get; set;}
}
In this example it would be like to return all Companies and order by PayrollNumber.
The Repository Method would look like this with standard linq.
var companies = session.Query<Company>()
.OrderBy(x => x.Pieces.FirstOrDefault().PayrollNo)
.FetchMany(x => x.Employees)
I would like to change this to dynamic linq to order by column headers
var companies = session.Query<Company>()
.OrderByName("Employees.PayrollNo"), isDescending)
.FetchMany(x => x.Employees)
I took an approach similar to the answer in Dynamic LINQ OrderBy on IEnumerable<T> Writing an extension method
But then drilled down with recursion
public static IQueryable<T> OrderByName<T>(this IQueryable<T> source, string propertyName, Boolean isDescending)
{
if (source == null) throw new ArgumentNullException("source");
if (propertyName == null) throw new ArgumentNullException("propertyName");
var properties = propertyName.Split('.');
var type = GetNestedProperty(properties, typeof(T));
var arg = Expression.Parameter(type.GetProperty(properties.Last()).PropertyType, "x");
var expr = Expression.Property(arg, properties.Last());
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
String methodName = isDescending ? "OrderByDescending" : "OrderBy";
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}
//Walk the tree of properties looking for the most nested in the string provided
static Type GetNestedProperty(string[] propertyChain, Type type)
{
if (propertyChain.Count() == 0)
return type;
string first = propertyChain.First();
propertyChain = propertyChain.Skip(1).ToArray(); //strip off first element
//We hare at the end of the hierarchy
if (propertyChain.Count() == 0)
return GetNestedProperty(propertyChain, type);
//Is Enumerable
if (type.GetProperty(first).PropertyType.GetInterfaces().Any(t => t.Name == "IEnumerable"))
return GetNestedProperty(
propertyChain,
type.GetProperty(first).PropertyType.GetGenericArguments()[0]);
return GetNestedProperty(
propertyChain,
type.GetProperty(first).PropertyType.GetProperty(propertyChain.FirstOrDefault()).GetType());
}
I am having difficulty generating the expression in the OrderByName extension method. I have tried quite a few things now, but the problem is that Payroll number does not exist in the Company class.
Is what I am trying to achieve even possible?
Any help with this would be greatly appreciated.