我希望能够在 linq 表达式中重构OrderBy子句。
这是一个重构where子句 的例子
前:
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() });
后:
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;
}
我想知道除了我想重构Orderby表达式之外,是否可以进行相同类型的事情。
先感谢您