如果我们强制查询语法返回IQueryable类型,那么我们就可以使用方法语法了。
在这里,我将查询更改为返回IQueryable类型:
IQueryable<Employee> filteredEmployees =
(from employee in allEmployees.AsQueryable()
where employee.DepartmentID < 4 && employee.EmployeeID < 10
orderby employee.DepartmentID descending,
employee.LastName descending
select employee);
Console.WriteLine(filteredEmployees.ToString());
在之前的代码中,我们将"AsQueryable()"添加到"allEmployees"列表类型中。现在返回类型将是IQueryable,所以"filteredEmployees"现在将是"IQueryable"类型。然后在"filteredEmployees"上,我们只需要调用"ToString()"方法。
并且以下内容将被写入控制台。
System.Collections.Generic.List`1[UserQuery+Employee]
.Where(employee => ((employee.DepartmentID < 4) AndAlso (employee.EmployeeID < 10)))
.OrderByDescending(employee => employee.DepartmentID)
.ThenByDescending(employee => employee.LastName)
虽然不完美,但我们可以轻松地将其编辑成以下形式
IEnumerable<Employee> filteredEmployees2 = allEmployees
.Where(employee => ((employee.DepartmentID < 4) && (employee.EmployeeID < 10)))
.OrderByDescending(employee => employee.DepartmentID)
.ThenByDescending(employee => employee.LastName);
Console.WriteLine(filteredEmployees);
在之前的代码中,我删除了"System.Collections.Generic.List`1[UserQuery+Employee]"并用"allEmployees"替换了它。 我还用"&&"替换了"AndAlso"。
这将返回与查询语法中相同的结果。