簡體   English   中英

Orderby不會調用所提供的比較器的Compare()

[英]Orderby doesn't call Compare() of the provided comparer

任何人都可以解釋為什么.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);
    }

它不起作用,因為您實際上並沒有評估orderedEmployees序列。 您需要使用ToListToArray強制進行評估。

Linq使用延遲執行,因此在以下位置定義您的排序查詢:

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

沒有做任何工作來實際訂購輸入序列。 只有當您嘗試使用查詢結果時才會完成排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM