如果我们强制查询语法返回一个 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”替换为“&&”。
这将返回与查询语法中的查询相同的结果。