I would like to be able to refactor out the OrderBy clause in a linq expression.
Here is an example of a refactor of the where clause
before:
results = ctx.ActiveUsers .Where(u => u.CompanyID != 1 && (u.LastName.ToLower().Contains(searchString) || u.Email.ToLower().Contains(searchString) || u.Company.Name.ToLower().Contains(searchString))) .OrderBy(u => u.LastName ).ThenBy(u => u.FirstName) .Select(u => new Employee { ID = u.ID , FirstName = u.FirstName , LastName = u.LastName , Email = u.Email , CompanyName = u.Company.Name , CompanyID = u.CompanyID.ToString() });
after:
results = ctx.ActiveUsers .Where(Employee.GetExpression(searchString)) .OrderBy(u => u.LastName ).ThenBy(u => u.FirstName) .Select(u => new Employee { ID = u.ID , FirstName = u.FirstName , LastName = u.LastName , Email = u.Email , CompanyName = u.Company.Name , CompanyID = u.CompanyID.ToString() });
private static Expression<Func<User, bool>> GetExpression(string searchString) { Expression<Func<User, bool>> p = (u => u.CompanyID != 1 && (u.LastName.ToLower().Contains(searchString) || u.Email.ToLower().Contains(searchString) || u.Company.Name.ToLower().Contains(searchString))); return p; }
I was wondering if the same type of thing would be possible except I would like to refactor the Orderby expression.
Thank you in advance
Assuming you want to actually take a string such as ‘LastName’, ‘FirstName’ etc, I’d do something like:
and add a new OrderBy extension method:
You certainly could do this using reflection, but unless you have a significant set of properties (or you want to use the same routine for different entity types) a switch statement is easier.