gpt4 book ai didi

c# - Orderby 不调用提供的比较器的 Compare()

转载 作者:行者123 更新时间:2023-11-30 13:38:33 25 4
gpt4 key购买 nike

任何人都可以解释为什么 .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 使用 deferred execution所以在以下位置定义您的订购查询:

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

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

关于c# - Orderby 不调用提供的比较器的 Compare(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16015260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com