1

As an example, I have the following classes -

public class Person 
{
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

public class Department 
{
   public Person Manager {get;set;}
}

Now I have a static method -

public static IQueryable<T> OrderByName<T>(this IQueryable<T> source, Expression<Func<T, Person>> expression)
   {
     // What I would like to achieve here -
     // from the 'expression' argument, create lambda expressions for FirstName & LastName
     // and then use it like -
     return source.OrderBy(firstNameExpression).ThenBy(lastNameExpression);
   }

Use,

// collection here is IQueryable<Deparment> type
collection.OrderByName(x => x.Manager);

So how can I create that static method to achieve this? Thanks.

Edit: This question had been marked as duplicate to this one - How do I compose Linq Expressions? ie Func<Exp<Func<X, Y>>, Exp<Func<Y, Z>>, Exp<Func<X, Z>>>

And this did not resolve my issue, or the answer there is incomplete for my scenario but it helped me in combination with other SOs (trying to re-find those links as source here).

SOLUTION

Since I cannot answer this question (marked as duplicate), I'll post my solution in the question body -

public static IQueryable<T> OrderByName<T>(this IQueryable<T> source, Expression<Func<T, Person>> expression)
   {
     Expression<Func<Person, string>> firstNameExp = p => p.FirstName;
     Expression<Func<Person, string>> lastNameExp = p => p.LastName;
     var paramEx = Expression.Parameter(typeof(T));
     Expression<Func<T, string>> firstNameLambda = Expression.Lambda<Func<T, string>>(Expression.Invoke(firstNameExp, Expression.Invoke(expression, paramEx)), paramEx);
     Expression<Func<T, string>> lastNameLambda = Expression.Lambda<Func<T, string>>(Expression.Invoke(lastNameExp, Expression.Invoke(expression, paramEx)), paramEx);
     return source.OrderBy(firstNameLambda ).ThenBy(lastNameLambda);
   }
Bandook
  • 658
  • 6
  • 21

0 Answers0