Orderby不会调用所提供的比较器的Compare()

时间:2013-04-15 12:32:58

标签: c# .net linq

任何人都可以解释为什么.net框架在我使用Enumerable.OrderBy时不会调用比较器的比较方法。而当我使用List.Sort()时它会被调用。

//以下代码取自StackOverFlow.com上的另一篇文章

class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
}


class Employee_SortBySalaryByAscendingOrder : IComparer<Employee>
{
    #region IComparer<Employee> Members

    public int Compare(Employee x, Employee y)
    {
        if (x.Salary > y.Salary) return 1;
        else if (x.Salary < y.Salary) return -1;
        else return 0;
    }

    #endregion
}


    private void TestSort(object sender, EventArgs e)
    {

        List<Employee> empList = new List<Employee>() 
                                {       
                                    new Employee { Name = "a", Salary = 14000 },
                                    new Employee { Name = "b", Salary = 13000 } 
                                };
        Employee_SortBySalaryByAscendingOrder eAsc = 
                    new Employee_SortBySalaryByAscendingOrder();
        // Sort Employees by salary by ascending order.   

        // Does not work
        IOrderedEnumerable<Employee> orderedEmployees = empList.OrderBy(x => x, eAsc);

        // Works
        empList.Sort(eAsc);
    }

1 个答案:

答案 0 :(得分:10)

它不起作用,因为您实际上并未评估orderedEmployees序列。您需要使用ToListToArray强制进行评估。

Linq使用deferred execution来定义您的订购查询:

IOrderedEnumerable<Employee> orderedEmployees = empList.OrderBy(x => x, eAsc);

没有做任何实际排序输入序列的工作。只有当您尝试使用查询结果时才会完成排序。