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