简体   繁体   English

仅使用Entity Framework LINQ优化查找最小值/最大值

[英]Optimize finding Min/Max value using Entity Framework LINQ only

The way I normally find the Min/Max in the database is using 我通常在数据库中找到最小/最大的方式是使用

var employeeWithMinSalary = employees.OrderBy(x=>x.Salary).First()
var employeeWithMaxSalary = employees.OrderByDescending(x=>x.Salary).First()

However, the performance is O(n * Log(n)). 但是,性能为O(n * Log(n))。

Is there any other way to Optimize the performance to O(n) using Linq only? 是否有其他方法可以仅使用Linq优化O(n)的性能? (No other libraries) (没有其他库)

It's not necessary to sort a list to find the Min/Max value from a list. 不必对列表进行排序即可从列表中查找“最小值/最大值”。 The best sorting algorithm has an average complexity of O(N*logN). 最佳排序算法的平均复杂度为O(N * logN)。 Both Max and Min operations shouldn't take more than O(N), even though the list is unsorted. 即使列表未排序,“最大”和“最小”操作的取值也不应超过O(N)。

You can implement the solution posted here or implementing the following code: 您可以实施此处发布的解决方案或实施以下代码:

   private static Employee MaxBySalary(List<Employee> employees)
    {
        Employee employee = null;
        employees.ForEach(x => employee = ( employee != null && employee.Salary > x.Salary) ? employee : x );
        return employee;
    }

    private static Employee MinBySalary(List<Employee> employees)
    {
        Employee employee = null;
        employees.ForEach(x => employee = (employee != null && employee.Salary < x.Salary) ? employee : x);
        return employee;
    }

Both approaches have O(N) complexity 两种方法都具有O(N)复杂度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM