按升序对数字进行排序和 IList c#
Sort and IList of numbers in ascending order c#
所以我遇到了这个我认为很简单但让我思考的问题。
任务是按升序对 Ilist 的数字进行排序。
据我所知,我们不能对 Ilists 使用 Sort() 方法,因为它不是在接口中构建的。
你能帮我对 Ilist 进行排序的最好和最简单的解决方案是什么吗?
IList<int> list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };
您可以简单地使用 Linq 来完成任务:
var list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };
var sorted = list.OrderBy(x => x);
如果要进行 in-place 排序,可以使用 ArrayList.Adapter()
根据文档:
The ArrayList class provides generic Reverse, BinarySearch and Sort
methods. This wrapper can be a means to use those methods on IList;
however, performing these generic operations through the wrapper might
be less efficient than operations applied directly on the IList.
如果您知道 List 的基础类型,您可以转换为 List 并使用 Sort 方法。
((List<int)list).Sort()
所以我遇到了这个我认为很简单但让我思考的问题。 任务是按升序对 Ilist 的数字进行排序。 据我所知,我们不能对 Ilists 使用 Sort() 方法,因为它不是在接口中构建的。 你能帮我对 Ilist 进行排序的最好和最简单的解决方案是什么吗?
IList<int> list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };
您可以简单地使用 Linq 来完成任务:
var list = new List<int>() { -5, 8, -7, 0, 44, 121, -7 };
var sorted = list.OrderBy(x => x);
如果要进行 in-place 排序,可以使用 ArrayList.Adapter()
根据文档:
The ArrayList class provides generic Reverse, BinarySearch and Sort methods. This wrapper can be a means to use those methods on IList; however, performing these generic operations through the wrapper might be less efficient than operations applied directly on the IList.
如果您知道 List 的基础类型,您可以转换为 List 并使用 Sort 方法。
((List<int)list).Sort()