79661837

Date: 2025-06-11 10:43:04
Score: 1
Natty:
Report link

How do I create an order-by expression that involves multiple fields?

orderByExpression = e => e.LastName || e.FirstName;

The answer depends on what you want.

Suppose you have the following three names:

I want to order by LastName, then by FirstName.

After ordering you want: Zebedeus Amsterdam, Albert Jansen Jan Jansen

IQueryable<Employee> employees = ...
IQueryable<Employee> orderedEmployees = employees.OrderBy(employee => employee.LastName)
                                                 .ThenBy(employee => employee.FirstName);

Usually it is quite hard to manipulate expressions directly. It's way easier to let LINQ do that on an IQueryable then creating the expression itself. If for some reason you really do need the Expression, consider to create the IQueryable on an empty sequence, and then extract the Expression.

IQueryable<Employee> emptyEmployees = Enumerable.Empty<Employee>()
                                                .AsQueryable()
                                                .OrderBy(employee => employee.LastName)
                                                .ThenBy(employee => employee.FirstName);
System.Linq.Expressions.Expression expression = emptyEmployees;

If you really want to create the Expression yourself, consider to familiarize yourself with class ExpressionVisitor. Read How to use ExpressionVisitor like a pro?

Reasons:
  • Blacklisted phrase (1): How do I
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Starts with a question (0.5): How do I
  • High reputation (-2):
Posted by: Harald Coppoolse